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
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportDigitalPortMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalChannel.java // public enum DigitalChannel { // // Map all pins to their digital channel ports // // First int is channel ID. Remaining are list of pins in channel. // Channel0 (0, 0, 1, 2, 3, 4, 5, 6), // Channel1 (1, 7, 8, 9, 10, 11, 12, 13), // Channel2 (2, 14, 15, 16, 17, 18, 19, 20), // Channel3 (3, 21, 22, 23, 24, 25, 26, 27); // // // Collection of the pins mapped to the channel // private ArrayList<Integer> pins; // // // Integer identifier of the enum // private Integer identifier; // // DigitalChannel(Integer identifier, Integer... pins) { // this.identifier = identifier; // this.pins = new ArrayList<>(Arrays.asList(pins)); // } // // /** // * Get a list of arduino pins associated with this channel // * @return ArrayList of 8 pins representing the channel // */ // public ArrayList<Integer> getPins() { // return pins; // } // // /** // * Get the identifier integer for this DigitanChannel // * @return Integer representing this DigitalChannel // */ // public Integer getIdentifier() { // return identifier; // } // // /** // * Check if this channel contains a specific Arduino pin within it. // * @param pin Integer value of the pin to check // * @return True if the channel contains the pin. False if not. // */ // public Boolean containsPin(Integer pin) { // return pins.contains(pin); // } // // /** // * Get the digital channel associated with the integer value given // * @param channelIdentifier Integer representing the channel to return (0 for channel 0) // * @return DigitalChannel representing the integer provided // */ // public static DigitalChannel getChannel(Integer channelIdentifier) { // for (DigitalChannel channel : DigitalChannel.values()) { // if (channel.getIdentifier().equals(channelIdentifier)) { // return channel; // } // } // // return null; // } // // /** // * Get a list of arduino pins associated with this channel // * @param channelIdentifier Integer value representing the channel (0 for channel0) // * @return ArrayList of 8 pins representing the channel // */ // public static ArrayList<Integer> getPins(Integer channelIdentifier) { // DigitalChannel channel = getChannel(channelIdentifier); // // if (channel != null) { // return channel.getPins(); // } // // return null; // } // // /** // * Gets the specific DigitalChannel that contains the requested Arduino pin // * @param pin Integer value of the pin that the desired channel should contain // * @return DigitalChannel that contains the given pin // */ // public static DigitalChannel getChannelForPin(Integer pin) { // for (DigitalChannel digitalChannel : DigitalChannel.values()) { // if (digitalChannel.getPins().contains(pin)) { // return digitalChannel; // } // } // // return null; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalChannel; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Digital Channel Message * Asks the Firmata Device to start reporting Digital values for the given channel (pin) */ public class ReportDigitalPortMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Digital Channel Message * @param digitalChannel DigitalChannel value for Firmata port. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalChannel.java // public enum DigitalChannel { // // Map all pins to their digital channel ports // // First int is channel ID. Remaining are list of pins in channel. // Channel0 (0, 0, 1, 2, 3, 4, 5, 6), // Channel1 (1, 7, 8, 9, 10, 11, 12, 13), // Channel2 (2, 14, 15, 16, 17, 18, 19, 20), // Channel3 (3, 21, 22, 23, 24, 25, 26, 27); // // // Collection of the pins mapped to the channel // private ArrayList<Integer> pins; // // // Integer identifier of the enum // private Integer identifier; // // DigitalChannel(Integer identifier, Integer... pins) { // this.identifier = identifier; // this.pins = new ArrayList<>(Arrays.asList(pins)); // } // // /** // * Get a list of arduino pins associated with this channel // * @return ArrayList of 8 pins representing the channel // */ // public ArrayList<Integer> getPins() { // return pins; // } // // /** // * Get the identifier integer for this DigitanChannel // * @return Integer representing this DigitalChannel // */ // public Integer getIdentifier() { // return identifier; // } // // /** // * Check if this channel contains a specific Arduino pin within it. // * @param pin Integer value of the pin to check // * @return True if the channel contains the pin. False if not. // */ // public Boolean containsPin(Integer pin) { // return pins.contains(pin); // } // // /** // * Get the digital channel associated with the integer value given // * @param channelIdentifier Integer representing the channel to return (0 for channel 0) // * @return DigitalChannel representing the integer provided // */ // public static DigitalChannel getChannel(Integer channelIdentifier) { // for (DigitalChannel channel : DigitalChannel.values()) { // if (channel.getIdentifier().equals(channelIdentifier)) { // return channel; // } // } // // return null; // } // // /** // * Get a list of arduino pins associated with this channel // * @param channelIdentifier Integer value representing the channel (0 for channel0) // * @return ArrayList of 8 pins representing the channel // */ // public static ArrayList<Integer> getPins(Integer channelIdentifier) { // DigitalChannel channel = getChannel(channelIdentifier); // // if (channel != null) { // return channel.getPins(); // } // // return null; // } // // /** // * Gets the specific DigitalChannel that contains the requested Arduino pin // * @param pin Integer value of the pin that the desired channel should contain // * @return DigitalChannel that contains the given pin // */ // public static DigitalChannel getChannelForPin(Integer pin) { // for (DigitalChannel digitalChannel : DigitalChannel.values()) { // if (digitalChannel.getPins().contains(pin)) { // return digitalChannel; // } // } // // return null; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportDigitalPortMessage.java import com.bortbort.arduino.FiloFirmata.DigitalChannel; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Digital Channel Message * Asks the Firmata Device to start reporting Digital values for the given channel (pin) */ public class ReportDigitalPortMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Digital Channel Message * @param digitalChannel DigitalChannel value for Firmata port. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */
public ReportDigitalPortMessage(DigitalChannel digitalChannel, Boolean enableReporting) {
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportDigitalPortMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalChannel.java // public enum DigitalChannel { // // Map all pins to their digital channel ports // // First int is channel ID. Remaining are list of pins in channel. // Channel0 (0, 0, 1, 2, 3, 4, 5, 6), // Channel1 (1, 7, 8, 9, 10, 11, 12, 13), // Channel2 (2, 14, 15, 16, 17, 18, 19, 20), // Channel3 (3, 21, 22, 23, 24, 25, 26, 27); // // // Collection of the pins mapped to the channel // private ArrayList<Integer> pins; // // // Integer identifier of the enum // private Integer identifier; // // DigitalChannel(Integer identifier, Integer... pins) { // this.identifier = identifier; // this.pins = new ArrayList<>(Arrays.asList(pins)); // } // // /** // * Get a list of arduino pins associated with this channel // * @return ArrayList of 8 pins representing the channel // */ // public ArrayList<Integer> getPins() { // return pins; // } // // /** // * Get the identifier integer for this DigitanChannel // * @return Integer representing this DigitalChannel // */ // public Integer getIdentifier() { // return identifier; // } // // /** // * Check if this channel contains a specific Arduino pin within it. // * @param pin Integer value of the pin to check // * @return True if the channel contains the pin. False if not. // */ // public Boolean containsPin(Integer pin) { // return pins.contains(pin); // } // // /** // * Get the digital channel associated with the integer value given // * @param channelIdentifier Integer representing the channel to return (0 for channel 0) // * @return DigitalChannel representing the integer provided // */ // public static DigitalChannel getChannel(Integer channelIdentifier) { // for (DigitalChannel channel : DigitalChannel.values()) { // if (channel.getIdentifier().equals(channelIdentifier)) { // return channel; // } // } // // return null; // } // // /** // * Get a list of arduino pins associated with this channel // * @param channelIdentifier Integer value representing the channel (0 for channel0) // * @return ArrayList of 8 pins representing the channel // */ // public static ArrayList<Integer> getPins(Integer channelIdentifier) { // DigitalChannel channel = getChannel(channelIdentifier); // // if (channel != null) { // return channel.getPins(); // } // // return null; // } // // /** // * Gets the specific DigitalChannel that contains the requested Arduino pin // * @param pin Integer value of the pin that the desired channel should contain // * @return DigitalChannel that contains the given pin // */ // public static DigitalChannel getChannelForPin(Integer pin) { // for (DigitalChannel digitalChannel : DigitalChannel.values()) { // if (digitalChannel.getPins().contains(pin)) { // return digitalChannel; // } // } // // return null; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalChannel; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Digital Channel Message * Asks the Firmata Device to start reporting Digital values for the given channel (pin) */ public class ReportDigitalPortMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Digital Channel Message * @param digitalChannel DigitalChannel value for Firmata port. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */ public ReportDigitalPortMessage(DigitalChannel digitalChannel, Boolean enableReporting) {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalChannel.java // public enum DigitalChannel { // // Map all pins to their digital channel ports // // First int is channel ID. Remaining are list of pins in channel. // Channel0 (0, 0, 1, 2, 3, 4, 5, 6), // Channel1 (1, 7, 8, 9, 10, 11, 12, 13), // Channel2 (2, 14, 15, 16, 17, 18, 19, 20), // Channel3 (3, 21, 22, 23, 24, 25, 26, 27); // // // Collection of the pins mapped to the channel // private ArrayList<Integer> pins; // // // Integer identifier of the enum // private Integer identifier; // // DigitalChannel(Integer identifier, Integer... pins) { // this.identifier = identifier; // this.pins = new ArrayList<>(Arrays.asList(pins)); // } // // /** // * Get a list of arduino pins associated with this channel // * @return ArrayList of 8 pins representing the channel // */ // public ArrayList<Integer> getPins() { // return pins; // } // // /** // * Get the identifier integer for this DigitanChannel // * @return Integer representing this DigitalChannel // */ // public Integer getIdentifier() { // return identifier; // } // // /** // * Check if this channel contains a specific Arduino pin within it. // * @param pin Integer value of the pin to check // * @return True if the channel contains the pin. False if not. // */ // public Boolean containsPin(Integer pin) { // return pins.contains(pin); // } // // /** // * Get the digital channel associated with the integer value given // * @param channelIdentifier Integer representing the channel to return (0 for channel 0) // * @return DigitalChannel representing the integer provided // */ // public static DigitalChannel getChannel(Integer channelIdentifier) { // for (DigitalChannel channel : DigitalChannel.values()) { // if (channel.getIdentifier().equals(channelIdentifier)) { // return channel; // } // } // // return null; // } // // /** // * Get a list of arduino pins associated with this channel // * @param channelIdentifier Integer value representing the channel (0 for channel0) // * @return ArrayList of 8 pins representing the channel // */ // public static ArrayList<Integer> getPins(Integer channelIdentifier) { // DigitalChannel channel = getChannel(channelIdentifier); // // if (channel != null) { // return channel.getPins(); // } // // return null; // } // // /** // * Gets the specific DigitalChannel that contains the requested Arduino pin // * @param pin Integer value of the pin that the desired channel should contain // * @return DigitalChannel that contains the given pin // */ // public static DigitalChannel getChannelForPin(Integer pin) { // for (DigitalChannel digitalChannel : DigitalChannel.values()) { // if (digitalChannel.getPins().contains(pin)) { // return digitalChannel; // } // } // // return null; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportDigitalPortMessage.java import com.bortbort.arduino.FiloFirmata.DigitalChannel; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Digital Channel Message * Asks the Firmata Device to start reporting Digital values for the given channel (pin) */ public class ReportDigitalPortMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Digital Channel Message * @param digitalChannel DigitalChannel value for Firmata port. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */ public ReportDigitalPortMessage(DigitalChannel digitalChannel, Boolean enableReporting) {
super(CommandBytes.REPORT_DIGITAL_PIN, digitalChannel.getIdentifier());
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SystemResetMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * System Reset Message * Asks the Firmata device to reboot/reset */ public class SystemResetMessage extends TransmittableMessage { public SystemResetMessage() {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SystemResetMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * System Reset Message * Asks the Firmata device to reboot/reset */ public class SystemResetMessage extends TransmittableMessage { public SystemResetMessage() {
super(CommandBytes.SYSTEM_RESET);
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexCapabilityQueryMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Capability Query Message * Asks the Firmata device to respond with a list of capable modes that a pin can support. */ public class SysexCapabilityQueryMessage extends TransmittableSysexMessage { public SysexCapabilityQueryMessage() {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexCapabilityQueryMessage.java import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Capability Query Message * Asks the Firmata device to respond with a list of capable modes that a pin can support. */ public class SysexCapabilityQueryMessage extends TransmittableSysexMessage { public SysexCapabilityQueryMessage() {
super(SysexCommandBytes.CAPABILITY_QUERY);
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Message * Enables transmitting of a Firmata command. * Supplies a system for serializing the message into a byte array to be sent over the wire. */ public abstract class TransmittableMessage implements Message { /** * CommandByte used to identify this message over the SerialPort communications line. */ byte commandByte; /** * Construct a new TransmittableMessage using a pre-defined Firmata CommandByte. * * @param commandByte CommandBytes commandByte identifying the command that this message is for. */
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Message * Enables transmitting of a Firmata command. * Supplies a system for serializing the message into a byte array to be sent over the wire. */ public abstract class TransmittableMessage implements Message { /** * CommandByte used to identify this message over the SerialPort communications line. */ byte commandByte; /** * Construct a new TransmittableMessage using a pre-defined Firmata CommandByte. * * @param commandByte CommandBytes commandByte identifying the command that this message is for. */
public TransmittableMessage(CommandBytes commandByte) {
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableChannelMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Channel Message * Enables transmitting of a Firmata command that is bit-masked with a channel port identifier byte (0-16) * Handles the masking of the two bytes into one, so that implementations only need focus on the two values * being sent down. Supplies a system for serializing the message into a byte array to be sent over the wire. */ public abstract class TransmittableChannelMessage extends TransmittableMessage { private byte channelByte;
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableChannelMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Channel Message * Enables transmitting of a Firmata command that is bit-masked with a channel port identifier byte (0-16) * Handles the masking of the two bytes into one, so that implementations only need focus on the two values * being sent down. Supplies a system for serializing the message into a byte array to be sent over the wire. */ public abstract class TransmittableChannelMessage extends TransmittableMessage { private byte channelByte;
public TransmittableChannelMessage(CommandBytes commandByte, int channelByte) {
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexPinStateMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.PinCapability;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Pin State Response Message * Contains the details for a specific Firmata pin, including its current PinCapability pinMode, the pin * value (High/Low) that was set by the user or PinMode (Pullup has pinValue or logic HIGH always since * it is enabling internal pullup). */ public class SysexPinStateMessage implements Message { private Integer pinIdentifier;
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexPinStateMessage.java import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.PinCapability; package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Pin State Response Message * Contains the details for a specific Firmata pin, including its current PinCapability pinMode, the pin * value (High/Low) that was set by the user or PinMode (Pullup has pinValue or logic HIGH always since * it is enabling internal pullup). */ public class SysexPinStateMessage implements Message { private Integer pinIdentifier;
private PinCapability currentPinMode;
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexPinStateMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.PinCapability;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Pin State Response Message * Contains the details for a specific Firmata pin, including its current PinCapability pinMode, the pin * value (High/Low) that was set by the user or PinMode (Pullup has pinValue or logic HIGH always since * it is enabling internal pullup). */ public class SysexPinStateMessage implements Message { private Integer pinIdentifier; private PinCapability currentPinMode; private Integer pinValue;
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexPinStateMessage.java import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.PinCapability; package com.bortbort.arduino.FiloFirmata.Messages; /** * Sysex Pin State Response Message * Contains the details for a specific Firmata pin, including its current PinCapability pinMode, the pin * value (High/Low) that was set by the user or PinMode (Pullup has pinValue or logic HIGH always since * it is enabling internal pullup). */ public class SysexPinStateMessage implements Message { private Integer pinIdentifier; private PinCapability currentPinMode; private Integer pinValue;
private DigitalPinValue digitalPinValue;
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetPinModeMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.PinCapability; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Pin Mode Message * Asks the Firmata device to set a PinCapability mode onto a given pin. This * tells the pin what data it should be handling, if its input or output, should enable the * internal pullup line, etc. */ public class SetPinModeMessage extends TransmittableMessage { int pinIdentifier;
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetPinModeMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.PinCapability; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Pin Mode Message * Asks the Firmata device to set a PinCapability mode onto a given pin. This * tells the pin what data it should be handling, if its input or output, should enable the * internal pullup line, etc. */ public class SetPinModeMessage extends TransmittableMessage { int pinIdentifier;
PinCapability pinMode;
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetPinModeMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.PinCapability; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Pin Mode Message * Asks the Firmata device to set a PinCapability mode onto a given pin. This * tells the pin what data it should be handling, if its input or output, should enable the * internal pullup line, etc. */ public class SetPinModeMessage extends TransmittableMessage { int pinIdentifier; PinCapability pinMode; /** * Set Pin Mode Message * @param pinIdentifier int Index representing the pin to perform this request on. * @param pinMode PinCapability mode to set the Firmata pin to (Input, Output, Analog, etc) */ public SetPinModeMessage(int pinIdentifier, PinCapability pinMode) {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/PinCapability.java // public enum PinCapability { // INPUT (0x00), // defined in Arduino.h DIGITAL IN LOW // OUTPUT (0x01), // defined in Arduino.h DIGITAL OUT // ANALOG (0x02), // ANALOG INPUT // PWM (0x03), // digital pin in PWM output mode "ANALOG" OUTPUT // SERVO (0x04), // digital pin in Servo output mode // SHIFT (0x05), // shiftIn/shiftOut mode // I2C (0x06), // pin included in I2C setup // ONEWIRE (0x07), // pin configured for 1-wire // STEPPER (0x08), // pin configured for stepper motor // ENCODER (0x09), // pin configured for rotary encoders // SERIAL (0x0A), // pin configured for serial communication // INPUT_PULLUP (0x0B), // enable internal pull-up resistor for pin DIGITAL IN HIGH // IGNORE (0x7F); // pin configured to be ignored by digitalWrite and capabilityResponse // // private byte identifierByte; // PinCapability(int identifierByte) { // this.identifierByte = (byte) identifierByte; // } // // public Byte getIdentifierByte() { // return identifierByte; // } // // public static ArrayList<PinCapability> getCapabilities(byte... identifierBytes) { // ArrayList<PinCapability> pinCapabilities = new ArrayList<>(); // for (byte identifierByte : identifierBytes) { // PinCapability pinCapability = getCapability(identifierByte); // if (pinCapability != null) { // pinCapabilities.add(pinCapability); // } // } // // if (pinCapabilities.isEmpty()) { // pinCapabilities.add(IGNORE); // } // // return pinCapabilities; // } // // public static PinCapability getCapability(byte identifierByte) { // for (PinCapability pinCapability : PinCapability.values()) { // if (pinCapability.getIdentifierByte() == identifierByte) { // return pinCapability; // } // } // // return null; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetPinModeMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.PinCapability; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Pin Mode Message * Asks the Firmata device to set a PinCapability mode onto a given pin. This * tells the pin what data it should be handling, if its input or output, should enable the * internal pullup line, etc. */ public class SetPinModeMessage extends TransmittableMessage { int pinIdentifier; PinCapability pinMode; /** * Set Pin Mode Message * @param pinIdentifier int Index representing the pin to perform this request on. * @param pinMode PinCapability mode to set the Firmata pin to (Input, Output, Analog, etc) */ public SetPinModeMessage(int pinIdentifier, PinCapability pinMode) {
super(CommandBytes.SET_PIN_MODE);
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableSysexMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Sysex Message * Enables transmitting of a Firmata Sysex command. Handles serialization of the root command byte for Sysex, * and the Sysex command byte that the message is for. * Supplies a system for serializing the Sysex message into a byte array to be sent over the wire. */ public abstract class TransmittableSysexMessage extends TransmittableMessage { /** * SysexCommandByte used to identify this sysex message over the SerialPort communications line. */ Byte sysexCommandByte; /** * Construct a new TransmittableSysexMessage using a pre-defined Firmata SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes sysexCommandByte identifying the sysex command * that this sysex message is for. */
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableSysexMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Sysex Message * Enables transmitting of a Firmata Sysex command. Handles serialization of the root command byte for Sysex, * and the Sysex command byte that the message is for. * Supplies a system for serializing the Sysex message into a byte array to be sent over the wire. */ public abstract class TransmittableSysexMessage extends TransmittableMessage { /** * SysexCommandByte used to identify this sysex message over the SerialPort communications line. */ Byte sysexCommandByte; /** * Construct a new TransmittableSysexMessage using a pre-defined Firmata SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes sysexCommandByte identifying the sysex command * that this sysex message is for. */
public TransmittableSysexMessage(SysexCommandBytes sysexCommandByte) {
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableSysexMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Sysex Message * Enables transmitting of a Firmata Sysex command. Handles serialization of the root command byte for Sysex, * and the Sysex command byte that the message is for. * Supplies a system for serializing the Sysex message into a byte array to be sent over the wire. */ public abstract class TransmittableSysexMessage extends TransmittableMessage { /** * SysexCommandByte used to identify this sysex message over the SerialPort communications line. */ Byte sysexCommandByte; /** * Construct a new TransmittableSysexMessage using a pre-defined Firmata SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes sysexCommandByte identifying the sysex command * that this sysex message is for. */ public TransmittableSysexMessage(SysexCommandBytes sysexCommandByte) { this(sysexCommandByte.getSysexCommandByte()); } /** * Construct a new TransmittableSysexMessage using a SysexCommandByte. * * @param sysexCommandByte SysexCommandByte identifying the sysex command that this sysex message is for. */ public TransmittableSysexMessage(Byte sysexCommandByte) {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexCommandBytes.java // public enum SysexCommandBytes { // ENCODER_DATA (0x61), // reply with encoders current positions // ANALOG_MAPPING_QUERY (0x69), // ask for mapping of analog to pin numbers // ANALOG_MAPPING_RESPONSE (0x6A), // reply with mapping info // CAPABILITY_QUERY (0x6B), // ask for supported modes and resolution of all pins // CAPABILITY_RESPONSE (0x6C), // reply with supported modes and resolution // PIN_STATE_QUERY (0x6D), // ask for a pin's current mode and state (different than value) // PIN_STATE_RESPONSE (0x6E), // reply with a pin's current mode and state (different than value) // EXTENDED_ANALOG (0x6F), // analog write (PWM, Servo, etc) to any pin // SERVO_CONFIG (0x70), // pin number and min and max pulse // STRING_DATA (0x71), // a string message with 14-bits per char // STEPPER_DATA (0x72), // control a stepper motor // ONEWIRE_DATA (0x73), // send an OneWire read/write/reset/select/skip/search request // SHIFT_DATA (0x75), // shiftOut config/data message (reserved - not yet implemented) // I2C_REQUEST (0x76), // I2C request messages from a host to an I/O board // I2C_REPLY (0x77), // I2C reply messages from an I/O board to a host // I2C_CONFIG (0x78), // Enable I2C and provide any configuration settings // REPORT_FIRMWARE (0x79), // report name and version of the firmware // SAMPLEING_INTERVAL (0x7A), // the interval at which analog input is sampled (default = 19ms) // SCHEDULER_DATA (0x7B), // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler // SYSEX_NON_REALTIME (0x7E), // MIDI Reserved for non-realtime messages // SYSEX_REALTIME (0x7F); // MIDI Reserved for realtime messages // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value. // */ // private byte sysexCommandByte; // // /** // * Construct enum with the provided sysexCommandByte. // * // * @param sysexCommandByte int representing the Firmata protocol sysex command byte. // */ // SysexCommandBytes(int sysexCommandByte) { // this.sysexCommandByte = (byte) sysexCommandByte; // } // // /** // * Sysex Command Byte representing the SysexCommandBytes enum value // * // * @return Byte representing the SysexCommandBytes enum value. // */ // public Byte getSysexCommandByte() { // return sysexCommandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/TransmittableSysexMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import com.bortbort.arduino.FiloFirmata.Parser.SysexCommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Transmittable Sysex Message * Enables transmitting of a Firmata Sysex command. Handles serialization of the root command byte for Sysex, * and the Sysex command byte that the message is for. * Supplies a system for serializing the Sysex message into a byte array to be sent over the wire. */ public abstract class TransmittableSysexMessage extends TransmittableMessage { /** * SysexCommandByte used to identify this sysex message over the SerialPort communications line. */ Byte sysexCommandByte; /** * Construct a new TransmittableSysexMessage using a pre-defined Firmata SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes sysexCommandByte identifying the sysex command * that this sysex message is for. */ public TransmittableSysexMessage(SysexCommandBytes sysexCommandByte) { this(sysexCommandByte.getSysexCommandByte()); } /** * Construct a new TransmittableSysexMessage using a SysexCommandByte. * * @param sysexCommandByte SysexCommandByte identifying the sysex command that this sysex message is for. */ public TransmittableSysexMessage(Byte sysexCommandByte) {
super(CommandBytes.START_SYSEX);
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetDigitalPinValueMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Digital Pin Value Message * Asks the Firmata device to set a digital logic level (high/low) on a given pin. * Note this does not use the 'Channel/Command byte' design like reporting does. No idea why. */ public class SetDigitalPinValueMessage extends TransmittableMessage { private int pinIdentifier;
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetDigitalPinValueMessage.java import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Digital Pin Value Message * Asks the Firmata device to set a digital logic level (high/low) on a given pin. * Note this does not use the 'Channel/Command byte' design like reporting does. No idea why. */ public class SetDigitalPinValueMessage extends TransmittableMessage { private int pinIdentifier;
private DigitalPinValue pinValue;
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetDigitalPinValueMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Digital Pin Value Message * Asks the Firmata device to set a digital logic level (high/low) on a given pin. * Note this does not use the 'Channel/Command byte' design like reporting does. No idea why. */ public class SetDigitalPinValueMessage extends TransmittableMessage { private int pinIdentifier; private DigitalPinValue pinValue; /** * Set Digital Pin Value Message * @param pinIdentifier int Index representing the pin to set the value on. * @param pinValue DigitalPinValue logic level high or low to set on the pin. */ public SetDigitalPinValueMessage(int pinIdentifier, DigitalPinValue pinValue) {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/DigitalPinValue.java // public enum DigitalPinValue { // LOW (0x00), // Digital Low // HIGH (0x01); // Digital High // // private Byte byteValue; // private Integer intValue; // // DigitalPinValue(int byteValue) { // this.byteValue = (byte) byteValue; // intValue = byteValue; // } // // /** // * Get Byte Value. // * @return Byte representing the digital logic pin value. // */ // public Byte getByteValue() { // return byteValue; // } // // /** // * Get Integer Value. // * @return Integer representing the digital logic pin value. // */ // public Integer getIntValue() { // return intValue; // } // // /** // * Translate to DigitalPinValue from a supplied Integer. // * @param pinValue Integer representing the digital value. // * @return DigitalPinValue representing the integer (High/Low). // */ // public static DigitalPinValue valueFromInt(Integer pinValue) { // return pinValue <= 0 ? LOW : HIGH; // } // // /** // * Translate to DigitalPinValue from a supplied Byte. // * @param byteValue Byte representing the digital value. // * @return DigitalPinValue representing the byte (High/Low). // */ // public static DigitalPinValue valueFromByte(Byte byteValue) { // return valueFromInt((int) byteValue); // } // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SetDigitalPinValueMessage.java import com.bortbort.arduino.FiloFirmata.DigitalPinValue; import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Set Digital Pin Value Message * Asks the Firmata device to set a digital logic level (high/low) on a given pin. * Note this does not use the 'Channel/Command byte' design like reporting does. No idea why. */ public class SetDigitalPinValueMessage extends TransmittableMessage { private int pinIdentifier; private DigitalPinValue pinValue; /** * Set Digital Pin Value Message * @param pinIdentifier int Index representing the pin to set the value on. * @param pinValue DigitalPinValue logic level high or low to set on the pin. */ public SetDigitalPinValueMessage(int pinIdentifier, DigitalPinValue pinValue) {
super(CommandBytes.SET_DIGITAL_PIN_VALUE);
reapzor/FiloFirmata
src/test/java/com/bortbort/arduino/FiloFirmata/PortAdapters/PureJavaCommSerialPortTest.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/FirmataHelper.java // public class FirmataHelper { // // private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); // public static String bytesToHexString(byte... bytes) { // char[] hexChars = new char[bytes.length * 2]; // for ( int j = 0; j < bytes.length; j++ ) { // int v = bytes[j] & 0xFF; // hexChars[j * 2] = hexArray[v >>> 4]; // hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // } // return new String(hexChars); // } // // public static String decodeTwoSevenBitByteString(byte[] bytes) throws UnsupportedEncodingException { // return decodeTwoSevenBitByteString(bytes, 0, bytes.length); // } // // public static String decodeTwoSevenBitByteString(byte[] bytes, int offset, int size) // throws UnsupportedEncodingException { // byte[] decodedBytes = decodeTwoSevenBitByteSequence(bytes, offset, size); // return new String(decodedBytes, "UTF-8"); // } // // public static byte[] decodeTwoSevenBitByteSequence(byte[] encodedBytes) { // return decodeTwoSevenBitByteSequence(encodedBytes, 0, encodedBytes.length); // } // // public static byte[] decodeTwoSevenBitByteSequence(byte[] encodedBytes, int offset, int size) { // size = size >>> 1; // ByteBuffer byteBuffer = ByteBuffer.allocate(size); // // for (int x = 0; x < size; x++) { // byteBuffer.put( // decodeTwoSevenBitByteSequence( // encodedBytes[offset++], // encodedBytes[offset++])); // } // // return byteBuffer.array(); // } // // public static byte decodeTwoSevenBitByteSequence(byte byte1, byte byte2) { // return (byte) (byte1 + (byte2 << 7)); // } // // // public static byte[] encodeTwoSevenBitByteSequence(String string) { // return encodeTwoSevenBitByteSequence(string.getBytes()); // } // // public static byte[] encodeTwoSevenBitByteSequence(byte... bytes) { // return encodeTwoSevenBitByteSequence(bytes, 0, bytes.length); // } // // public static byte[] encodeTwoSevenBitByteSequence(byte[] bytes, int offset, int size) { // int encodedSize = size * 2; // ByteBuffer byteBuffer = ByteBuffer.allocate(encodedSize); // // for (int x = offset; x < size; x++) { // // Mask by 01111111 as we only want to preserve the first 7 bits only // byteBuffer.put((byte) (bytes[x] & 0x7F)); // // Shift the byte over by 7 bits // byteBuffer.put((byte) (bytes[x] >>> 7 & 0x7f)); // } // // return byteBuffer.array(); // } // // // public static Boolean fastReadBytesWithTimeout(InputStream inputStream, // byte[] buffer, long timeout) throws IOException { // return fastReadBytesWithTimeout(inputStream, buffer, buffer.length, timeout); // } // // public static Boolean fastReadBytesWithTimeout(InputStream inputStream, // byte[] buffer, int length, // long timeout) throws IOException { // int readByteCount = 0; // long timeoutTime = System.currentTimeMillis() + timeout; // // while (System.currentTimeMillis() < timeoutTime && readByteCount < length) { // int readByte = inputStream.read(); // if (readByte == -1) { // return false; // } // else { // buffer[readByteCount] = (byte) readByte; // readByteCount += 1; // } // } // // return true; // } // // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexReportFirmwareQueryMessage.java // public class SysexReportFirmwareQueryMessage extends TransmittableSysexMessage { // // public SysexReportFirmwareQueryMessage() { // super(SysexCommandBytes.REPORT_FIRMWARE); // } // // /** // * When transmitting the request for a SysexReportFirmware message, we need no body data, only the command // * to be sent, which is handled by the parent class. Treat the implementation as a no-op and return // * no body. This will ensure the output is {0xF9 0x79 0xF7} (start_sysex, report_firmware, end_sysex). // * // * @return true. // */ // @Override // protected Boolean serialize(ByteArrayOutputStream outputStream) { // return true; // } // // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SystemResetMessage.java // public class SystemResetMessage extends TransmittableMessage { // // public SystemResetMessage() { // super(CommandBytes.SYSTEM_RESET); // } // // @Override // protected Boolean serialize(ByteArrayOutputStream outputStream) { // return true; // } // }
import com.bortbort.arduino.FiloFirmata.FirmataHelper; import com.bortbort.arduino.FiloFirmata.Messages.SysexReportFirmwareQueryMessage; import com.bortbort.arduino.FiloFirmata.Messages.SystemResetMessage; import org.junit.Test; import static org.junit.Assert.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.bortbort.arduino.FiloFirmata.PortAdapters; /** * Created by chuck on 1/3/2016. */ public class PureJavaCommSerialPortTest { protected static final Logger log = LoggerFactory.getLogger(PureJavaCommSerialPortTest.class); // f0 = sysex start. 79 = firmware report. 02 05 = version (2.5). "filename". f7 = sysex end. // f0 79 02 05 StandardFirmata.ino f7 private static final String expectedResponseBytes = "F07902055300740061006E006400610072006400460069" + "0072006D006100740061002E0069006E006F00F7"; PureJavaCommSerialPort serialPort = new PureJavaCommSerialPort("COM3", 57600); @Test public void testDataRXTX() throws Exception { assertTrue("Unable to connect serial port!", serialPort.connect()); // Reset
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/FirmataHelper.java // public class FirmataHelper { // // private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); // public static String bytesToHexString(byte... bytes) { // char[] hexChars = new char[bytes.length * 2]; // for ( int j = 0; j < bytes.length; j++ ) { // int v = bytes[j] & 0xFF; // hexChars[j * 2] = hexArray[v >>> 4]; // hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // } // return new String(hexChars); // } // // public static String decodeTwoSevenBitByteString(byte[] bytes) throws UnsupportedEncodingException { // return decodeTwoSevenBitByteString(bytes, 0, bytes.length); // } // // public static String decodeTwoSevenBitByteString(byte[] bytes, int offset, int size) // throws UnsupportedEncodingException { // byte[] decodedBytes = decodeTwoSevenBitByteSequence(bytes, offset, size); // return new String(decodedBytes, "UTF-8"); // } // // public static byte[] decodeTwoSevenBitByteSequence(byte[] encodedBytes) { // return decodeTwoSevenBitByteSequence(encodedBytes, 0, encodedBytes.length); // } // // public static byte[] decodeTwoSevenBitByteSequence(byte[] encodedBytes, int offset, int size) { // size = size >>> 1; // ByteBuffer byteBuffer = ByteBuffer.allocate(size); // // for (int x = 0; x < size; x++) { // byteBuffer.put( // decodeTwoSevenBitByteSequence( // encodedBytes[offset++], // encodedBytes[offset++])); // } // // return byteBuffer.array(); // } // // public static byte decodeTwoSevenBitByteSequence(byte byte1, byte byte2) { // return (byte) (byte1 + (byte2 << 7)); // } // // // public static byte[] encodeTwoSevenBitByteSequence(String string) { // return encodeTwoSevenBitByteSequence(string.getBytes()); // } // // public static byte[] encodeTwoSevenBitByteSequence(byte... bytes) { // return encodeTwoSevenBitByteSequence(bytes, 0, bytes.length); // } // // public static byte[] encodeTwoSevenBitByteSequence(byte[] bytes, int offset, int size) { // int encodedSize = size * 2; // ByteBuffer byteBuffer = ByteBuffer.allocate(encodedSize); // // for (int x = offset; x < size; x++) { // // Mask by 01111111 as we only want to preserve the first 7 bits only // byteBuffer.put((byte) (bytes[x] & 0x7F)); // // Shift the byte over by 7 bits // byteBuffer.put((byte) (bytes[x] >>> 7 & 0x7f)); // } // // return byteBuffer.array(); // } // // // public static Boolean fastReadBytesWithTimeout(InputStream inputStream, // byte[] buffer, long timeout) throws IOException { // return fastReadBytesWithTimeout(inputStream, buffer, buffer.length, timeout); // } // // public static Boolean fastReadBytesWithTimeout(InputStream inputStream, // byte[] buffer, int length, // long timeout) throws IOException { // int readByteCount = 0; // long timeoutTime = System.currentTimeMillis() + timeout; // // while (System.currentTimeMillis() < timeoutTime && readByteCount < length) { // int readByte = inputStream.read(); // if (readByte == -1) { // return false; // } // else { // buffer[readByteCount] = (byte) readByte; // readByteCount += 1; // } // } // // return true; // } // // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SysexReportFirmwareQueryMessage.java // public class SysexReportFirmwareQueryMessage extends TransmittableSysexMessage { // // public SysexReportFirmwareQueryMessage() { // super(SysexCommandBytes.REPORT_FIRMWARE); // } // // /** // * When transmitting the request for a SysexReportFirmware message, we need no body data, only the command // * to be sent, which is handled by the parent class. Treat the implementation as a no-op and return // * no body. This will ensure the output is {0xF9 0x79 0xF7} (start_sysex, report_firmware, end_sysex). // * // * @return true. // */ // @Override // protected Boolean serialize(ByteArrayOutputStream outputStream) { // return true; // } // // } // // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/SystemResetMessage.java // public class SystemResetMessage extends TransmittableMessage { // // public SystemResetMessage() { // super(CommandBytes.SYSTEM_RESET); // } // // @Override // protected Boolean serialize(ByteArrayOutputStream outputStream) { // return true; // } // } // Path: src/test/java/com/bortbort/arduino/FiloFirmata/PortAdapters/PureJavaCommSerialPortTest.java import com.bortbort.arduino.FiloFirmata.FirmataHelper; import com.bortbort.arduino.FiloFirmata.Messages.SysexReportFirmwareQueryMessage; import com.bortbort.arduino.FiloFirmata.Messages.SystemResetMessage; import org.junit.Test; import static org.junit.Assert.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.bortbort.arduino.FiloFirmata.PortAdapters; /** * Created by chuck on 1/3/2016. */ public class PureJavaCommSerialPortTest { protected static final Logger log = LoggerFactory.getLogger(PureJavaCommSerialPortTest.class); // f0 = sysex start. 79 = firmware report. 02 05 = version (2.5). "filename". f7 = sysex end. // f0 79 02 05 StandardFirmata.ino f7 private static final String expectedResponseBytes = "F07902055300740061006E006400610072006400460069" + "0072006D006100740061002E0069006E006F00F7"; PureJavaCommSerialPort serialPort = new PureJavaCommSerialPort("COM3", 57600); @Test public void testDataRXTX() throws Exception { assertTrue("Unable to connect serial port!", serialPort.connect()); // Reset
serialPort.getOutputStream().write(new SystemResetMessage().toByteArray());
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexMessageBuilder.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/Message.java // public interface Message { // // }
import com.bortbort.arduino.FiloFirmata.Messages.Message;
package com.bortbort.arduino.FiloFirmata.Parser; /** * SysexMessageBuilder definition for building Firmata Sysex Message objects from a determined byte array. */ public abstract class SysexMessageBuilder extends MessageBuilderBase { /** * Construct a SysexMessageBuilder using the given SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes enum value representing a Firmata sysex command byte. */ public SysexMessageBuilder(SysexCommandBytes sysexCommandByte) { super(sysexCommandByte.getSysexCommandByte()); } /** * Construct a SysexMessageBuilder using the given sysexCommandByte. * * @param sysexCommandByte Byte value representing a Firmata sysex command byte. */ public SysexMessageBuilder(byte sysexCommandByte) { super(sysexCommandByte); } /** * Build a Sysex Message from the given byte array. * * @param messageBody Byte array containing the serialized byte data representing the Sysex Message. * @return Firmata Sysex Message object representing the data obtained from the byte array. */
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/Message.java // public interface Message { // // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/SysexMessageBuilder.java import com.bortbort.arduino.FiloFirmata.Messages.Message; package com.bortbort.arduino.FiloFirmata.Parser; /** * SysexMessageBuilder definition for building Firmata Sysex Message objects from a determined byte array. */ public abstract class SysexMessageBuilder extends MessageBuilderBase { /** * Construct a SysexMessageBuilder using the given SysexCommandByte. * * @param sysexCommandByte SysexCommandBytes enum value representing a Firmata sysex command byte. */ public SysexMessageBuilder(SysexCommandBytes sysexCommandByte) { super(sysexCommandByte.getSysexCommandByte()); } /** * Construct a SysexMessageBuilder using the given sysexCommandByte. * * @param sysexCommandByte Byte value representing a Firmata sysex command byte. */ public SysexMessageBuilder(byte sysexCommandByte) { super(sysexCommandByte); } /** * Build a Sysex Message from the given byte array. * * @param messageBody Byte array containing the serialized byte data representing the Sysex Message. * @return Firmata Sysex Message object representing the data obtained from the byte array. */
public abstract Message buildMessage(byte[] messageBody);
reapzor/FiloFirmata
src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportAnalogPinMessage.java
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // }
import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream;
package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Analog Channel Message * Asks the Firmata Device to start reporting Analog values for the given channel (pin) */ public class ReportAnalogPinMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Analog Channel Message * @param pinIdentifier int Index value for Firmata pin. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */ public ReportAnalogPinMessage(int pinIdentifier, Boolean enableReporting) {
// Path: src/main/java/com/bortbort/arduino/FiloFirmata/Parser/CommandBytes.java // public enum CommandBytes { // DIGITAL_MESSAGE (0x90), // REPORT_ANALOG_PIN (0xC0), // REPORT_DIGITAL_PIN (0xD0), // ANALOG_MESSAGE (0xE0), // START_SYSEX (0xF0), // Start of SYSEX packet. Used by SysexCommandParser. // SET_PIN_MODE (0xF4), // SET_DIGITAL_PIN_VALUE (0xF5), // END_SYSEX (0xF7), // End of SYSEX packet. Used by SysexCommandParser. // PROTOCOL_VERSION (0xF9), // SYSTEM_RESET (0xFF); // // /** // * Command Byte representing the CommandBytes enum value. // */ // byte commandByte; // // /** // * Construct enum with the provided commandByte. // * // * @param commandByte int representing the Firmata protocol command byte. // */ // CommandBytes(int commandByte) { // this.commandByte = (byte) commandByte; // } // // /** // * Command Byte representing the CommandBytes enum value. // * // * @return Byte representing the CommandBytes enum value. // */ // public Byte getCommandByte() { // return commandByte; // } // } // Path: src/main/java/com/bortbort/arduino/FiloFirmata/Messages/ReportAnalogPinMessage.java import com.bortbort.arduino.FiloFirmata.Parser.CommandBytes; import java.io.ByteArrayOutputStream; package com.bortbort.arduino.FiloFirmata.Messages; /** * Report Analog Channel Message * Asks the Firmata Device to start reporting Analog values for the given channel (pin) */ public class ReportAnalogPinMessage extends TransmittableChannelMessage { Boolean enableReporting; /** * Report Analog Channel Message * @param pinIdentifier int Index value for Firmata pin. * @param enableReporting Boolean value to enable or disable reporting. (True = enable) */ public ReportAnalogPinMessage(int pinIdentifier, Boolean enableReporting) {
super(CommandBytes.REPORT_ANALOG_PIN, pinIdentifier);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException;
package fr.tikione.steam.cleaner.util.conf; /** * I18n language files encoding handler. */ public class I18nEncoding { /** Singleton handler. */ private static final I18nEncoding i18nEncoding; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; static { // Singleton creation. try { i18nEncoding = new I18nEncoding(); } catch (IOException ex) { Log.error(ex); throw new RuntimeException(ex); } } /** * Get the configuration handler as a singleton. * * @return the configuration handler singleton. */ public static synchronized I18nEncoding getInstance() { return i18nEncoding; } /** * Load application configuration file. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. */ private I18nEncoding() throws IOException { configFile = new File("conf/i18n/encoding.ini"); ini = new Ini(); ini.getConfig().enableParseLineConcat(true); ini.getConfig().enableReadUnicodeEscConv(true);
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // } // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException; package fr.tikione.steam.cleaner.util.conf; /** * I18n language files encoding handler. */ public class I18nEncoding { /** Singleton handler. */ private static final I18nEncoding i18nEncoding; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; static { // Singleton creation. try { i18nEncoding = new I18nEncoding(); } catch (IOException ex) { Log.error(ex); throw new RuntimeException(ex); } } /** * Get the configuration handler as a singleton. * * @return the configuration handler singleton. */ public static synchronized I18nEncoding getInstance() { return i18nEncoding; } /** * Load application configuration file. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. */ private I18nEncoding() throws IOException { configFile = new File("conf/i18n/encoding.ini"); ini = new Ini(); ini.getConfig().enableParseLineConcat(true); ini.getConfig().enableReadUnicodeEscConv(true);
ini.load(configFile, Main.CONF_ENCODING);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/conf/DangerousItems.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException;
package fr.tikione.steam.cleaner.util.conf; /** * List of items patterns to exclude from the search path. */ public class DangerousItems { private static final DangerousItems dangerousItems; /** INI configuration file section : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS = "AUTOEXCLUDE_PATTERNS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS__FOLDERS_LIST = "folderPatterns"; /** File to use for configuration loading and saving. */ private static File configFile; /** Configuration object. */ private static Ini ini; static { // Singleton creation. try { dangerousItems = new DangerousItems(); } catch (IOException ex) {
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // } // Path: src/fr/tikione/steam/cleaner/util/conf/DangerousItems.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; package fr.tikione.steam.cleaner.util.conf; /** * List of items patterns to exclude from the search path. */ public class DangerousItems { private static final DangerousItems dangerousItems; /** INI configuration file section : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS = "AUTOEXCLUDE_PATTERNS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS__FOLDERS_LIST = "folderPatterns"; /** File to use for configuration loading and saving. */ private static File configFile; /** Configuration object. */ private static Ini ini; static { // Singleton creation. try { dangerousItems = new DangerousItems(); } catch (IOException ex) {
Log.error(ex);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/conf/DangerousItems.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException;
package fr.tikione.steam.cleaner.util.conf; /** * List of items patterns to exclude from the search path. */ public class DangerousItems { private static final DangerousItems dangerousItems; /** INI configuration file section : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS = "AUTOEXCLUDE_PATTERNS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS__FOLDERS_LIST = "folderPatterns"; /** File to use for configuration loading and saving. */ private static File configFile; /** Configuration object. */ private static Ini ini; static { // Singleton creation. try { dangerousItems = new DangerousItems(); } catch (IOException ex) { Log.error(ex); throw new RuntimeException(ex); } } /** * Get the configuration handler as a singleton. * * @return the configuration handler singleton. */ public static synchronized DangerousItems getInstance() { return dangerousItems; } /** * Load application configuration file. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. */ private DangerousItems() throws IOException { configFile = new File("conf/tikione-steam-cleaner_dangerous-items.ini"); ini = new Ini(); ini.getConfig().enableParseLineConcat(true); ini.getConfig().enableReadUnicodeEscConv(true);
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/Log.java // public class Log { // // /** Default logger. */ // protected static Logger messagesLogger; // // static { // try { // Properties conf = new Properties(); // File backupLog4j = new File("conf/backup/tikione-steam-cleaner_log4j.properties"); // File userprofile = new File(Config.getProfilePath()); // userprofile.mkdirs(); // File userLog4j = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_log4j.properties"); // if (!userLog4j.exists()) { // org.apache.commons.io.FileUtils.copyFile(backupLog4j, userLog4j); // } // conf.load(new FileReader(userLog4j)); // conf.setProperty("log4j.appender.messages.File", Config.getProfilePath() + "/log/steamcleaner_messages.log"); // PropertyConfigurator.configure(conf); // messagesLogger = Logger.getLogger("fr.tikione.steam.cleaner.log.info"); // } catch (IOException ex) { // throw new RuntimeException("Cannot instantiate Log4j", ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Log() { // } // // /** // * Log a message object with the INFO Level. // * // * @param message the emssage to log. // */ // public static void info(String message) { // messagesLogger.info(message); // } // // /** // * Log a message object with the ERROR Level. // * // * @param ex the exception to log. // */ // public static void error(Throwable ex) { // messagesLogger.error("", ex); // } // // /** // * Log a message object with the ERROR Level. // * // * @param message the emssage to log. // * @param ex the exception to log. // */ // public static void error(String message, Throwable ex) { // messagesLogger.error(message, ex); // } // } // Path: src/fr/tikione/steam/cleaner/util/conf/DangerousItems.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.Log; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; package fr.tikione.steam.cleaner.util.conf; /** * List of items patterns to exclude from the search path. */ public class DangerousItems { private static final DangerousItems dangerousItems; /** INI configuration file section : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS = "AUTOEXCLUDE_PATTERNS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_AUTOEXCLUDE_PATTERNS__FOLDERS_LIST = "folderPatterns"; /** File to use for configuration loading and saving. */ private static File configFile; /** Configuration object. */ private static Ini ini; static { // Singleton creation. try { dangerousItems = new DangerousItems(); } catch (IOException ex) { Log.error(ex); throw new RuntimeException(ex); } } /** * Get the configuration handler as a singleton. * * @return the configuration handler singleton. */ public static synchronized DangerousItems getInstance() { return dangerousItems; } /** * Load application configuration file. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. */ private DangerousItems() throws IOException { configFile = new File("conf/tikione-steam-cleaner_dangerous-items.ini"); ini = new Ini(); ini.getConfig().enableParseLineConcat(true); ini.getConfig().enableReadUnicodeEscConv(true);
ini.load(configFile, Main.CONF_ENCODING);
wbsdty331/TikiOne-steam-Cleaner-Plus
old Files/src/fr/tikione/steam/cleaner/util/Translation.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException;
package fr.tikione.steam.cleaner.util; /** * Translation handler. */ public class Translation { private static final String DEFAULT_LANGCODE = "en"; private static final String CONF_GLOBAL_SECTION = ""; public static final String CONF_BASEPATH = "conf/i18n/"; public static final String CONF_BASEPATH_FLAGS = CONF_BASEPATH + "flags/"; private static final String CONF_EXT = ".ini"; private Ini iniLang; public static final String SEC_WMAIN = "W_MAIN"; public static final String SEC_WABOUT = "W_ABOUT"; public static final String SEC_WCHECKFORUPDATES = "W_CHECKFORUPDATES"; public static final String SEC_DELETE = "W_DELETE"; public static final String SEC_OPTIONS = "W_OPTIONS"; public Translation(String localeCode) { try { iniLang = new Ini();
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // } // Path: old Files/src/fr/tikione/steam/cleaner/util/Translation.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; package fr.tikione.steam.cleaner.util; /** * Translation handler. */ public class Translation { private static final String DEFAULT_LANGCODE = "en"; private static final String CONF_GLOBAL_SECTION = ""; public static final String CONF_BASEPATH = "conf/i18n/"; public static final String CONF_BASEPATH_FLAGS = CONF_BASEPATH + "flags/"; private static final String CONF_EXT = ".ini"; private Ini iniLang; public static final String SEC_WMAIN = "W_MAIN"; public static final String SEC_WABOUT = "W_ABOUT"; public static final String SEC_WCHECKFORUPDATES = "W_CHECKFORUPDATES"; public static final String SEC_DELETE = "W_DELETE"; public static final String SEC_OPTIONS = "W_OPTIONS"; public Translation(String localeCode) { try { iniLang = new Ini();
String lngEncoding = I18nEncoding.getInstance().getLngEncoding(localeCode);
wbsdty331/TikiOne-steam-Cleaner-Plus
old Files/src/fr/tikione/steam/cleaner/util/Translation.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException;
*/ public String getString(String key) { return getString(CONF_GLOBAL_SECTION, key); } /** * Get a translated string denoted by an identifier and a section name. * * @param section * @param key the string identifier. * @return the translated string. */ public String getString(String section, String key) { try { return iniLang.getKeyValue(" ??? ", section, key); } catch (CharConversionException | InfinitiveLoopException ex) { Log.error(ex); return " ??? "; } } public static List<CountryLanguage> getAvailLangList() throws IOException, CharConversionException, InfinitiveLoopException { List<CountryLanguage> langList = new ArrayList<>(2); File i18nFolder = new File(CONF_BASEPATH); File[] langFiles = i18nFolder.listFiles((File dir, String name) -> name.endsWith(CONF_EXT) && !name.equalsIgnoreCase("encoding.ini")); Ini langIni = new Ini(); for (File langFile : langFiles) {
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // } // Path: old Files/src/fr/tikione/steam/cleaner/util/Translation.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; */ public String getString(String key) { return getString(CONF_GLOBAL_SECTION, key); } /** * Get a translated string denoted by an identifier and a section name. * * @param section * @param key the string identifier. * @return the translated string. */ public String getString(String section, String key) { try { return iniLang.getKeyValue(" ??? ", section, key); } catch (CharConversionException | InfinitiveLoopException ex) { Log.error(ex); return " ??? "; } } public static List<CountryLanguage> getAvailLangList() throws IOException, CharConversionException, InfinitiveLoopException { List<CountryLanguage> langList = new ArrayList<>(2); File i18nFolder = new File(CONF_BASEPATH); File[] langFiles = i18nFolder.listFiles((File dir, String name) -> name.endsWith(CONF_EXT) && !name.equalsIgnoreCase("encoding.ini")); Ini langIni = new Ini(); for (File langFile : langFiles) {
langIni.load(langFile, Main.CONF_ENCODING);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/conf/UncheckedItems.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher;
package fr.tikione.steam.cleaner.util.conf; /** * List of unchecked items in the redistributable packages list. */ public class UncheckedItems { /** INI configuration file section : unchecked items. */ private static final String CONFIG_UNCHECKED_REDIST_ITEMS = "UNCHECKED_REDIST_ITEMS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_UNCHECKED_REDIST_ITEMS__ITEM_LIST = "itemList"; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; private boolean updated = false; /** * Load application configuration file. A default configuration file is created if necessary. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file, or while writing this default * configuration file. */ public UncheckedItems() throws IOException { File backupConfigFile = new File("conf/backup/tikione-steam-cleaner_unchecked-items.ini"); File userprofile = new File(Config.getProfilePath()); userprofile.mkdirs(); configFile = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_unchecked-items.ini"); if (!configFile.exists()) { org.apache.commons.io.FileUtils.copyFile(backupConfigFile, configFile); } ini = new Ini(); ini.getConfig().enableParseLineConcat(false); ini.getConfig().enableReadUnicodeEscConv(false);
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // Path: src/fr/tikione/steam/cleaner/util/conf/UncheckedItems.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; package fr.tikione.steam.cleaner.util.conf; /** * List of unchecked items in the redistributable packages list. */ public class UncheckedItems { /** INI configuration file section : unchecked items. */ private static final String CONFIG_UNCHECKED_REDIST_ITEMS = "UNCHECKED_REDIST_ITEMS"; /** INI configuration file key : unchecked items. */ private static final String CONFIG_UNCHECKED_REDIST_ITEMS__ITEM_LIST = "itemList"; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; private boolean updated = false; /** * Load application configuration file. A default configuration file is created if necessary. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file, or while writing this default * configuration file. */ public UncheckedItems() throws IOException { File backupConfigFile = new File("conf/backup/tikione-steam-cleaner_unchecked-items.ini"); File userprofile = new File(Config.getProfilePath()); userprofile.mkdirs(); configFile = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_unchecked-items.ini"); if (!configFile.exists()) { org.apache.commons.io.FileUtils.copyFile(backupConfigFile, configFile); } ini = new Ini(); ini.getConfig().enableParseLineConcat(false); ini.getConfig().enableReadUnicodeEscConv(false);
ini.load(configFile, Main.CONF_ENCODING);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/conf/CustomFolders.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher;
package fr.tikione.steam.cleaner.util.conf; /** * List of custom folders for redistributable packages research. */ public class CustomFolders { /** INI configuration file section : custom folders. */ private static final String CONFIG_CUSTOM_FOLDERS = "CUSTOM_FOLDERS"; /** INI configuration file key : custom folders. */ private static final String CONFIG_CUSTOM_FOLDERS__ITEM_LIST = "itemList"; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; private boolean updated = false; /** * Load application configuration file. A default configuration file is created if necessary. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file, or while writing this default * configuration file. */ public CustomFolders() throws IOException { File backupConfigFile = new File("conf/backup/tikione-steam-cleaner_custom-folders.ini"); File userprofile = new File(Config.getProfilePath()); userprofile.mkdirs(); configFile = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_custom-folders.ini"); if (!configFile.exists()) { org.apache.commons.io.FileUtils.copyFile(backupConfigFile, configFile); } ini = new Ini(); ini.getConfig().enableParseLineConcat(false); ini.getConfig().enableReadUnicodeEscConv(false);
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // Path: src/fr/tikione/steam/cleaner/util/conf/CustomFolders.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; package fr.tikione.steam.cleaner.util.conf; /** * List of custom folders for redistributable packages research. */ public class CustomFolders { /** INI configuration file section : custom folders. */ private static final String CONFIG_CUSTOM_FOLDERS = "CUSTOM_FOLDERS"; /** INI configuration file key : custom folders. */ private static final String CONFIG_CUSTOM_FOLDERS__ITEM_LIST = "itemList"; /** File to use for configuration loading and saving. */ private final File configFile; /** Configuration object. */ private final Ini ini; private boolean updated = false; /** * Load application configuration file. A default configuration file is created if necessary. * * @throws IOException if an I/O error occurs while retrieving the internal default configuration file, or while writing this default * configuration file. */ public CustomFolders() throws IOException { File backupConfigFile = new File("conf/backup/tikione-steam-cleaner_custom-folders.ini"); File userprofile = new File(Config.getProfilePath()); userprofile.mkdirs(); configFile = new File(userprofile.getAbsolutePath() + "/tikione-steam-cleaner_custom-folders.ini"); if (!configFile.exists()) { org.apache.commons.io.FileUtils.copyFile(backupConfigFile, configFile); } ini = new Ini(); ini.getConfig().enableParseLineConcat(false); ini.getConfig().enableReadUnicodeEscConv(false);
ini.load(configFile, Main.CONF_ENCODING);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/Translation.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException;
package fr.tikione.steam.cleaner.util; /** * Translation handler. */ public class Translation { private static final String DEFAULT_LANGCODE = "en"; private static final String CONF_GLOBAL_SECTION = ""; public static final String CONF_BASEPATH = "conf/i18n/"; public static final String CONF_BASEPATH_FLAGS = CONF_BASEPATH + "flags/"; private static final String CONF_EXT = ".ini"; private Ini iniLang; public static final String SEC_WMAIN = "W_MAIN"; public static final String SEC_WABOUT = "W_ABOUT"; public static final String SEC_WCHECKFORUPDATES = "W_CHECKFORUPDATES"; public static final String SEC_DELETE = "W_DELETE"; public static final String SEC_OPTIONS = "W_OPTIONS"; public Translation(String localeCode) { try { iniLang = new Ini();
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // } // Path: src/fr/tikione/steam/cleaner/util/Translation.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; package fr.tikione.steam.cleaner.util; /** * Translation handler. */ public class Translation { private static final String DEFAULT_LANGCODE = "en"; private static final String CONF_GLOBAL_SECTION = ""; public static final String CONF_BASEPATH = "conf/i18n/"; public static final String CONF_BASEPATH_FLAGS = CONF_BASEPATH + "flags/"; private static final String CONF_EXT = ".ini"; private Ini iniLang; public static final String SEC_WMAIN = "W_MAIN"; public static final String SEC_WABOUT = "W_ABOUT"; public static final String SEC_WCHECKFORUPDATES = "W_CHECKFORUPDATES"; public static final String SEC_DELETE = "W_DELETE"; public static final String SEC_OPTIONS = "W_OPTIONS"; public Translation(String localeCode) { try { iniLang = new Ini();
String lngEncoding = I18nEncoding.getInstance().getLngEncoding(localeCode);
wbsdty331/TikiOne-steam-Cleaner-Plus
src/fr/tikione/steam/cleaner/util/Translation.java
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // }
import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException;
*/ public String getString(String key) { return getString(CONF_GLOBAL_SECTION, key); } /** * Get a translated string denoted by an identifier and a section name. * * @param section * @param key the string identifier. * @return the translated string. */ public String getString(String section, String key) { try { return iniLang.getKeyValue(" ??? ", section, key); } catch (CharConversionException | InfinitiveLoopException ex) { Log.error(ex); return " ??? "; } } public static List<CountryLanguage> getAvailLangList() throws IOException, CharConversionException, InfinitiveLoopException { List<CountryLanguage> langList = new ArrayList<>(2); File i18nFolder = new File(CONF_BASEPATH); File[] langFiles = i18nFolder.listFiles((File dir, String name) -> name.endsWith(CONF_EXT) && !name.equalsIgnoreCase("encoding.ini")); Ini langIni = new Ini(); for (File langFile : langFiles) {
// Path: old Files/src/fr/tikione/steam/cleaner/Main.java // public class Main { // // public static final String CONF_ENCODING = StandardCharsets.UTF_8.name(); // public static final String CONF_NEWLINE = "\r\n"; // public static final Locale SYS_LOCALE = Locale.getDefault(); // public static boolean ARG_PORTABLE; // public static boolean BUNDLED_JVM; // // /** // * The application launcher. Starts GUI. // * // * @param args command-line arguments. // */ // public static void main(String[] args) { // // // Detect bundled JVM. // File jre = new File("./jre/"); // BUNDLED_JVM = jre.isDirectory() && jre.exists(); // // Log.info("-------------------------------------------------"); // Log.info("Application started; version is " + Version.VERSION // + "; default encoding is " + CONF_ENCODING // + "; default locale is " + SYS_LOCALE.toString() // + "; bundledJVM " + (BUNDLED_JVM ? "present" : "not found, will use system JVM")); // try { // javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // Log.error(e); // } // try { // JFrameMain gui = new JFrameMain(); // gui.setVisible(true); // } catch (IOException | InfinitiveLoopException ex) { // Log.error(ex); // } // } // // /** Suppresses default constructor, ensuring non-instantiability. */ // private Main() { // } // } // // Path: src/fr/tikione/steam/cleaner/util/conf/I18nEncoding.java // public class I18nEncoding { // // /** Singleton handler. */ // private static final I18nEncoding i18nEncoding; // // /** File to use for configuration loading and saving. */ // private final File configFile; // // /** Configuration object. */ // private final Ini ini; // // static { // // Singleton creation. // try { // i18nEncoding = new I18nEncoding(); // } catch (IOException ex) { // Log.error(ex); // throw new RuntimeException(ex); // } // } // // /** // * Get the configuration handler as a singleton. // * // * @return the configuration handler singleton. // */ // public static synchronized I18nEncoding getInstance() { // return i18nEncoding; // } // // /** // * Load application configuration file. // * // * @throws IOException if an I/O error occurs while retrieving the internal default configuration file. // */ // private I18nEncoding() // throws IOException { // configFile = new File("conf/i18n/encoding.ini"); // ini = new Ini(); // ini.getConfig().enableParseLineConcat(true); // ini.getConfig().enableReadUnicodeEscConv(true); // ini.load(configFile, Main.CONF_ENCODING); // } // // public String getLngEncoding(String locale) // throws CharConversionException, // InfinitiveLoopException { // return ini.getKeyValue(Main.CONF_ENCODING, "", locale); // } // } // Path: src/fr/tikione/steam/cleaner/util/Translation.java import fr.tikione.ini.InfinitiveLoopException; import fr.tikione.ini.Ini; import fr.tikione.steam.cleaner.Main; import fr.tikione.steam.cleaner.util.conf.I18nEncoding; import java.io.CharConversionException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; */ public String getString(String key) { return getString(CONF_GLOBAL_SECTION, key); } /** * Get a translated string denoted by an identifier and a section name. * * @param section * @param key the string identifier. * @return the translated string. */ public String getString(String section, String key) { try { return iniLang.getKeyValue(" ??? ", section, key); } catch (CharConversionException | InfinitiveLoopException ex) { Log.error(ex); return " ??? "; } } public static List<CountryLanguage> getAvailLangList() throws IOException, CharConversionException, InfinitiveLoopException { List<CountryLanguage> langList = new ArrayList<>(2); File i18nFolder = new File(CONF_BASEPATH); File[] langFiles = i18nFolder.listFiles((File dir, String name) -> name.endsWith(CONF_EXT) && !name.equalsIgnoreCase("encoding.ini")); Ini langIni = new Ini(); for (File langFile : langFiles) {
langIni.load(langFile, Main.CONF_ENCODING);
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceCDIIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jglue.cdiunit.CdiRunner; import org.jglue.cdiunit.jaxrs.SupportJaxRs; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.Mock; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(CdiRunner.class) @SupportJaxRs /** * This is no full integration test as we test agains the Java API but it shows how to use CDI in a test environment */ public class ItemRestServiceCDIIT { @Produces @Mock
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceCDIIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jglue.cdiunit.CdiRunner; import org.jglue.cdiunit.jaxrs.SupportJaxRs; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.Mock; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(CdiRunner.class) @SupportJaxRs /** * This is no full integration test as we test agains the Java API but it shows how to use CDI in a test environment */ public class ItemRestServiceCDIIT { @Produces @Mock
ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceCDIIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jglue.cdiunit.CdiRunner; import org.jglue.cdiunit.jaxrs.SupportJaxRs; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.Mock; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(CdiRunner.class) @SupportJaxRs /** * This is no full integration test as we test agains the Java API but it shows how to use CDI in a test environment */ public class ItemRestServiceCDIIT { @Produces @Mock ItemDAO itemDAO; @Inject ItemRestService itemRestService; @Before public void setup() {
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceCDIIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jglue.cdiunit.CdiRunner; import org.jglue.cdiunit.jaxrs.SupportJaxRs; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.Mock; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(CdiRunner.class) @SupportJaxRs /** * This is no full integration test as we test agains the Java API but it shows how to use CDI in a test environment */ public class ItemRestServiceCDIIT { @Produces @Mock ItemDAO itemDAO; @Inject ItemRestService itemRestService; @Before public void setup() {
ArrayList<Item> items = new ArrayList<Item>() {{
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import java.util.ArrayList; import java.util.List; import java.util.Observer;
package nl.han.dea.exercises.model; public class Course { Teacher teacher; List<Observer> attendees; public Course() { attendees = new ArrayList<Observer>(); }
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import java.util.ArrayList; import java.util.List; import java.util.Observer; package nl.han.dea.exercises.model; public class Course { Teacher teacher; List<Observer> attendees; public Course() { attendees = new ArrayList<Observer>(); }
public void startCourse() throws NoTeacherException, NoAttendeesException {
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import java.util.ArrayList; import java.util.List; import java.util.Observer;
package nl.han.dea.exercises.model; public class Course { Teacher teacher; List<Observer> attendees; public Course() { attendees = new ArrayList<Observer>(); }
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import java.util.ArrayList; import java.util.List; import java.util.Observer; package nl.han.dea.exercises.model; public class Course { Teacher teacher; List<Observer> attendees; public Course() { attendees = new ArrayList<Observer>(); }
public void startCourse() throws NoTeacherException, NoAttendeesException {
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/local/LocalItemServiceTest.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.when;
package oose.dea.services.local; @RunWith(MockitoJUnitRunner.class) public class LocalItemServiceTest { @Mock
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/local/LocalItemServiceTest.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.when; package oose.dea.services.local; @RunWith(MockitoJUnitRunner.class) public class LocalItemServiceTest { @Mock
ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/local/LocalItemServiceTest.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.when;
package oose.dea.services.local; @RunWith(MockitoJUnitRunner.class) public class LocalItemServiceTest { @Mock ItemDAO itemDAO; @InjectMocks LocalItemService localItemService;
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/local/LocalItemServiceTest.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.when; package oose.dea.services.local; @RunWith(MockitoJUnitRunner.class) public class LocalItemServiceTest { @Mock ItemDAO itemDAO; @InjectMocks LocalItemService localItemService;
private ArrayList<Item> items;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import java.util.List;
package oose.dea.services.local; public class LocalItemService implements ItemService { @Inject
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import java.util.List; package oose.dea.services.local; public class LocalItemService implements ItemService { @Inject
private ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import java.util.List;
package oose.dea.services.local; public class LocalItemService implements ItemService { @Inject private ItemDAO itemDAO; @Override
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import java.util.List; package oose.dea.services.local; public class LocalItemService implements ItemService { @Inject private ItemDAO itemDAO; @Override
public List<Item> findAll() {
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages";
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { {
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages"; // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { {
property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages";
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { {
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages"; // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { {
property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages";
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { { property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER); register(new TestBinder()); register(ItemRestService.class); } }; } private static class TestBinder extends AbstractBinder { @Override protected void configure() {
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages"; // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { { property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER); register(new TestBinder()); register(ItemRestService.class); } }; } private static class TestBinder extends AbstractBinder { @Override protected void configure() {
bindFactory(ServiceProvider.class).to(ItemDAO.class);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages";
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { { property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER); register(new TestBinder()); register(ItemRestService.class); } }; } private static class TestBinder extends AbstractBinder { @Override protected void configure() { bindFactory(ServiceProvider.class).to(ItemDAO.class); } } private static class ServiceProvider implements Factory<ItemDAO>{ @Override public ItemDAO provide() { ItemDAO itemDAO = mock(ItemDAO.class);
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JACKSON_JSON_SERIALIZER = "com.fasterxml.jackson.jaxrs.json;service"; // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/GuiceResourceConfig.java // public static final String JSON_SERIALIZER = "jersey.config.server.provider.packages"; // Path: examples/simpleorder-javaee/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import javax.ws.rs.core.Application; import java.util.ArrayList; import static oose.dea.config.GuiceResourceConfig.JACKSON_JSON_SERIALIZER; import static oose.dea.config.GuiceResourceConfig.JSON_SERIALIZER; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) public class ItemRestServiceIT extends JerseyTest { @Test public void findAll() throws Exception { final String items = target("/items").request().get(String.class); assertEquals("[{\"sku\":\"frik\",\"category\":\"Vette hap\",\"title\":\"Frikandel\"}]", items); } @Override protected Application configure() { return new ResourceConfig() { { property(JSON_SERIALIZER, JACKSON_JSON_SERIALIZER); register(new TestBinder()); register(ItemRestService.class); } }; } private static class TestBinder extends AbstractBinder { @Override protected void configure() { bindFactory(ServiceProvider.class).to(ItemDAO.class); } } private static class ServiceProvider implements Factory<ItemDAO>{ @Override public ItemDAO provide() { ItemDAO itemDAO = mock(ItemDAO.class);
ArrayList<Item> items = new ArrayList<Item>() {{
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;
package oose.dea.controller; @Singleton @WebServlet(urlPatterns = "/viewItems") public class ViewItemsPageController extends HttpServlet { @Inject
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; package oose.dea.controller; @Singleton @WebServlet(urlPatterns = "/viewItems") public class ViewItemsPageController extends HttpServlet { @Inject
private ItemService itemService;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;
package oose.dea.controller; @Singleton @WebServlet(urlPatterns = "/viewItems") public class ViewItemsPageController extends HttpServlet { @Inject private ItemService itemService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; package oose.dea.controller; @Singleton @WebServlet(urlPatterns = "/viewItems") public class ViewItemsPageController extends HttpServlet { @Inject private ItemService itemService; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Item> items = itemService.findAll();
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService;
package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets();
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets();
serve("/viewItems").with(ViewItemsPageController.class);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService;
package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class);
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class);
bind(ItemService.class).to(LocalItemService.class);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService;
package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class);
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class);
bind(ItemService.class).to(LocalItemService.class);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService;
package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class); bind(ItemService.class).to(LocalItemService.class);
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class); bind(ItemService.class).to(LocalItemService.class);
bind(ItemDAO.class).to(ItemJdbcDAO.class);
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // }
import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService;
package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class); bind(ItemService.class).to(LocalItemService.class);
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/controller/ViewItemsPageController.java // @Singleton // @WebServlet(urlPatterns = "/viewItems") // public class ViewItemsPageController extends HttpServlet { // @Inject // private ItemService itemService; // // protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // List<Item> items = itemService.findAll(); // request.setAttribute("all", items); // request.getRequestDispatcher("viewItems.jsp").forward(request, response); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/dataaccess/ItemJdbcDAO.java // @Default // public class ItemJdbcDAO implements ItemDAO { // private static Logger logger = Logger.getLogger(ItemJdbcDAO.class.getName()); // // private JdbcConnectionFactory jdbcConnectionFactory; // // @Inject // public ItemJdbcDAO(JdbcConnectionFactory jdbcConnectionFactory) { // this.jdbcConnectionFactory = jdbcConnectionFactory; // } // // @Override // public void add(Item entity) { // Connection connection = jdbcConnectionFactory.create(); // try { // PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO items VALUES (NULL, ? , ? , ?)"); // preparedStatement.setString(1, entity.getSku()); // preparedStatement.setString(2, entity.getCategory()); // preparedStatement.setString(3, entity.getTitle()); // preparedStatement.executeUpdate(); // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // } // // @Override // public void update(Item updatedEntity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public void remove(Item entity) { // throw new RuntimeException("Not implemented yet"); // } // // @Override // public List<Item> list() { // Connection connection = jdbcConnectionFactory.create(); // List<Item> items = new ArrayList<Item>(); // try { // ResultSet rs = connection.prepareStatement("SELECT * FROM items").executeQuery(); // while (rs.next()) { // items.add(new Item(rs.getString("sku"),rs.getString("category"),rs.getString("title"))); // } // connection.close(); // } catch (SQLException e) { // logger.severe(e.getMessage()); // } // return items; // } // // @Override // public Item find(int id) { // throw new RuntimeException("Not implemented yet"); // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/local/LocalItemService.java // public class LocalItemService implements ItemService { // @Inject // private ItemDAO itemDAO; // // @Override // public List<Item> findAll() { // return itemDAO.list(); // } // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/config/AppBinding.java import com.google.inject.servlet.ServletModule; import oose.dea.controller.ViewItemsPageController; import oose.dea.dataaccess.ItemDAO; import oose.dea.dataaccess.ItemJdbcDAO; import oose.dea.services.ItemService; import oose.dea.services.local.LocalItemService; package oose.dea.config; public class AppBinding extends ServletModule { @Override protected void configureServlets() { super.configureServlets(); serve("/viewItems").with(ViewItemsPageController.class); bind(ItemService.class).to(LocalItemService.class);
bind(ItemDAO.class).to(ItemJdbcDAO.class);
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.ws.rs.core.Response; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(MockitoJUnitRunner.class) public class ItemRestServiceIT extends RestEasyIT { @InjectMocks ItemRestService restService; @Mock
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.ws.rs.core.Response; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(MockitoJUnitRunner.class) public class ItemRestServiceIT extends RestEasyIT { @InjectMocks ItemRestService restService; @Mock
ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // }
import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.ws.rs.core.Response; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when;
package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(MockitoJUnitRunner.class) public class ItemRestServiceIT extends RestEasyIT { @InjectMocks ItemRestService restService; @Mock ItemDAO itemDAO; public ItemRestServiceIT() { super(ItemRestService.class); } @Override protected Object getServiceInstance() { return restService; } @Override public void setupDependencies() {
// Path: examples/simpleorder-javaee/src/test/java/oose/dea/IntegrationTest.java // public interface IntegrationTest { // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // Path: examples/simpleorder-javaee-cdi/src/test/java/oose/dea/services/rest/ItemRestServiceIT.java import oose.dea.IntegrationTest; import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.ws.rs.core.Response; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; package oose.dea.services.rest; @Category(IntegrationTest.class) @RunWith(MockitoJUnitRunner.class) public class ItemRestServiceIT extends RestEasyIT { @InjectMocks ItemRestService restService; @Mock ItemDAO itemDAO; public ItemRestServiceIT() { super(ItemRestService.class); } @Override protected Object getServiceInstance() { return restService; } @Override public void setupDependencies() {
ArrayList<Item> items = new ArrayList<Item>() {{
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/local/LocalItemService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Default; import javax.inject.Inject; import java.util.List;
package oose.dea.services.local; @Default public class LocalItemService implements ItemService { @Inject
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/local/LocalItemService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Default; import javax.inject.Inject; import java.util.List; package oose.dea.services.local; @Default public class LocalItemService implements ItemService { @Inject
private ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/local/LocalItemService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Default; import javax.inject.Inject; import java.util.List;
package oose.dea.services.local; @Default public class LocalItemService implements ItemService { @Inject private ItemDAO itemDAO; @Override
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/local/LocalItemService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Default; import javax.inject.Inject; import java.util.List; package oose.dea.services.local; @Default public class LocalItemService implements ItemService { @Inject private ItemDAO itemDAO; @Override
public List<Item> findAll() {
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List;
package oose.dea.services.rest; @Path("/items") @Alternative
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; package oose.dea.services.rest; @Path("/items") @Alternative
public class ItemRestService implements ItemService {
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List;
package oose.dea.services.rest; @Path("/items") @Alternative public class ItemRestService implements ItemService { @Inject
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; package oose.dea.services.rest; @Path("/items") @Alternative public class ItemRestService implements ItemService { @Inject
private ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List;
package oose.dea.services.rest; @Path("/items") @Alternative public class ItemRestService implements ItemService { @Inject private ItemDAO itemDAO; @GET @Produces(MediaType.APPLICATION_JSON)
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee-cdi/src/main/java/oose/dea/services/rest/ItemRestService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; package oose.dea.services.rest; @Path("/items") @Alternative public class ItemRestService implements ItemService { @Inject private ItemDAO itemDAO; @GET @Produces(MediaType.APPLICATION_JSON)
public List<Item> findAll() {
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/services/rest/ItemRestService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List;
package oose.dea.services.rest; @Path("/items") public class ItemRestService implements ItemService { @Inject
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/rest/ItemRestService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; package oose.dea.services.rest; @Path("/items") public class ItemRestService implements ItemService { @Inject
private ItemDAO itemDAO;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/main/java/oose/dea/services/rest/ItemRestService.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List;
package oose.dea.services.rest; @Path("/items") public class ItemRestService implements ItemService { @Inject private ItemDAO itemDAO; @GET @Produces(MediaType.APPLICATION_JSON)
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/ItemDAO.java // public interface ItemDAO extends DAO<Item>{ // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/rest/ItemRestService.java import oose.dea.dataaccess.Item; import oose.dea.dataaccess.ItemDAO; import oose.dea.services.ItemService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; package oose.dea.services.rest; @Path("/items") public class ItemRestService implements ItemService { @Inject private ItemDAO itemDAO; @GET @Produces(MediaType.APPLICATION_JSON)
public List<Item> findAll() {
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/controller/ViewItemsPageControllerTest.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package oose.dea.controller; @RunWith(MockitoJUnitRunner.class) public class ViewItemsPageControllerTest { @Mock
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/test/java/oose/dea/controller/ViewItemsPageControllerTest.java import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package oose.dea.controller; @RunWith(MockitoJUnitRunner.class) public class ViewItemsPageControllerTest { @Mock
ItemService itemService;
ddoa/dea-code-examples
examples/simpleorder-javaee/src/test/java/oose/dea/controller/ViewItemsPageControllerTest.java
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // }
import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package oose.dea.controller; @RunWith(MockitoJUnitRunner.class) public class ViewItemsPageControllerTest { @Mock ItemService itemService; @Mock HttpServletRequest httpServletRequest; @Mock HttpServletResponse httpServletResponse; @Mock RequestDispatcher requestDispatcher; @InjectMocks private ViewItemsPageController viewPageController;
// Path: examples/simpleorder-javaee/src/main/java/oose/dea/dataaccess/Item.java // public class Item { // private String sku; // private String category; // private String title; // // public Item() { // } // // public Item(String sku, String category, String title) { // this.sku = sku; // this.category = category; // this.title = title; // } // // public String getSku() { // return sku; // } // // public void setSku(String sku) { // this.sku = sku; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: examples/simpleorder-javaee/src/main/java/oose/dea/services/ItemService.java // public interface ItemService { // List<Item> findAll(); // } // Path: examples/simpleorder-javaee/src/test/java/oose/dea/controller/ViewItemsPageControllerTest.java import oose.dea.dataaccess.Item; import oose.dea.services.ItemService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package oose.dea.controller; @RunWith(MockitoJUnitRunner.class) public class ViewItemsPageControllerTest { @Mock ItemService itemService; @Mock HttpServletRequest httpServletRequest; @Mock HttpServletResponse httpServletResponse; @Mock RequestDispatcher requestDispatcher; @InjectMocks private ViewItemsPageController viewPageController;
private ArrayList<Item> items;
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher;
package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) {
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher; package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) {
Course course = new Course();
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher;
package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course();
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher; package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course();
course.addAttendee(new Student("Piet", course));
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher;
package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course));
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher; package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course));
course.addAttendee(new Teacher("Michel"));
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher;
package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course)); course.addAttendee(new Teacher("Michel")); course.setTeacher(new Teacher("Meron")); try { course.startCourse();
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher; package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course)); course.addAttendee(new Teacher("Michel")); course.setTeacher(new Teacher("Meron")); try { course.startCourse();
} catch (NoTeacherException e) {
ddoa/dea-code-examples
exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // }
import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher;
package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course)); course.addAttendee(new Teacher("Michel")); course.setTeacher(new Teacher("Meron")); try { course.startCourse(); } catch (NoTeacherException e) { System.out.println("Course wasn't started, since there is no teacher available.");
// Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoAttendeesException.java // public class NoAttendeesException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/exceptions/NoTeacherException.java // public class NoTeacherException extends Exception { // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Course.java // public class Course { // // Teacher teacher; // List<Observer> attendees; // // public Course() { // attendees = new ArrayList<Observer>(); // } // // public void startCourse() throws NoTeacherException, NoAttendeesException { // if (teacher == null) { // throw new NoTeacherException(); // } else if (attendees.isEmpty()) { // throw new NoAttendeesException(); // } // for (Observer attendee : attendees) { // teacher.addObserver(attendee); // } // teacher.teach(); // } // // public void addAttendee(Observer attendee) { // attendees.add(attendee); // } // // public void setTeacher(Teacher teacher) { // this.teacher = teacher; // } // // public void leave(Observer attendee) { // this.teacher.deleteObserver(attendee); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Student.java // public class Student implements Observer { // // private final String name; // private final Course course; // // private int numberOfNotes = 10; // // public Student(String name, Course course) { // // this.name = name; // this.course = course; // } // // private void makeNotes(String note) { // System.out.println("Student " + name + " made note: \n" + note); // // numberOfNotes--; // // if (numberOfNotes == 0) { // System.out.println("Student " + name + " has left the classroom"); // course.leave(this); // } // } // // public void update(Observable o, Object arg) { // makeNotes((String) arg); // } // } // // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/model/Teacher.java // public class Teacher extends Observable implements Observer{ // // private final String name; // private Teachings teachings; // // public Teacher(String name) { // this.name = name; // this.teachings = Teachings.getInstance(); // } // // public void teach() { // while (countObservers() > 0) { // // String wisdom = teachings.getWisdom(); // say(wisdom); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // System.out.println("Where have all my students gone?"); // } // // private void say(String wisdom) { // setChanged(); // notifyObservers(wisdom); // } // // public void update(Observable o, Object arg) { // System.out.println("hmmmm, intersting way of putting things."); // } // } // Path: exercises/observing-the-teacher/src/main/java/nl/han/dea/exercises/CourseApp.java import nl.han.dea.exercises.exceptions.NoAttendeesException; import nl.han.dea.exercises.exceptions.NoTeacherException; import nl.han.dea.exercises.model.Course; import nl.han.dea.exercises.model.Student; import nl.han.dea.exercises.model.Teacher; package nl.han.dea.exercises; public class CourseApp { public static void main(String[] args) { Course course = new Course(); course.addAttendee(new Student("Piet", course)); course.addAttendee(new Student("Karel", course)); course.addAttendee(new Student("Kees", course)); course.addAttendee(new Student("Martine", course)); course.addAttendee(new Teacher("Michel")); course.setTeacher(new Teacher("Meron")); try { course.startCourse(); } catch (NoTeacherException e) { System.out.println("Course wasn't started, since there is no teacher available.");
} catch (NoAttendeesException e) {
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadCapacityResponse { public static final int LENGTH = 8; private final int mBlockSize; private final int mNumberOfBlocks; public ReadCapacityResponse(byte[] answer) {
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadCapacityResponse { public static final int LENGTH = 8; private final int mBlockSize; private final int mNumberOfBlocks; public ReadCapacityResponse(byte[] answer) {
mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/test/java/net/alphadev/usbstorage/test/CapacityResponseTest.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class CapacityResponseTest { @Test public void doesNotComplainOnValidValues() {
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/test/java/net/alphadev/usbstorage/test/CapacityResponseTest.java import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class CapacityResponseTest { @Test public void doesNotComplainOnValidValues() {
byte[] data = BitStitching.forceCast(new int[]{
alphadev-net/drive-mount
scsi/src/test/java/net/alphadev/usbstorage/test/CapacityResponseTest.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class CapacityResponseTest { @Test public void doesNotComplainOnValidValues() { byte[] data = BitStitching.forceCast(new int[]{ 0x07, 0x33, 0xf3, 0xf3, 0x00, 0x00, 0x02, 0x00 });
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/test/java/net/alphadev/usbstorage/test/CapacityResponseTest.java import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class CapacityResponseTest { @Test public void doesNotComplainOnValidValues() { byte[] data = BitStitching.forceCast(new int[]{ 0x07, 0x33, 0xf3, 0xf3, 0x00, 0x00, 0x02, 0x00 });
final ReadCapacityResponse capacity = new ReadCapacityResponse(data);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesHeader.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadFormatCapacitiesHeader { public static final int LENGTH = 12; private byte mCapacityListLength; private int mNumberOfBlocks; private DescriptorType mDescriptorType; private int mBlockLength; public ReadFormatCapacitiesHeader(byte[] answer) { /** first three bits are reserved **/ mCapacityListLength = answer[3]; boolean hasValidNumOfEntries = mCapacityListLength % 8 == 0; int numOfEntries = mCapacityListLength / 8; if (!hasValidNumOfEntries || numOfEntries <= 0 || numOfEntries >= 256) { throw new IllegalArgumentException("Invalid CapacityListLength!"); } mCapacityListLength = (byte) numOfEntries;
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesHeader.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadFormatCapacitiesHeader { public static final int LENGTH = 12; private byte mCapacityListLength; private int mNumberOfBlocks; private DescriptorType mDescriptorType; private int mBlockLength; public ReadFormatCapacitiesHeader(byte[] answer) { /** first three bits are reserved **/ mCapacityListLength = answer[3]; boolean hasValidNumOfEntries = mCapacityListLength % 8 == 0; int numOfEntries = mCapacityListLength / 8; if (!hasValidNumOfEntries || numOfEntries <= 0 || numOfEntries >= 256) { throw new IllegalArgumentException("Invalid CapacityListLength!"); } mCapacityListLength = (byte) numOfEntries;
mNumberOfBlocks = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadFormatCapacities.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadFormatCapacities extends ScsiCommand { private static final byte READ_FORMAT_CAPACITIES = 0x23; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_FORMAT_CAPACITIES; // opcode
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadFormatCapacities.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadFormatCapacities extends ScsiCommand { private static final byte READ_FORMAT_CAPACITIES = 0x23; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_FORMAT_CAPACITIES; // opcode
BitStitching.setBytesFromShort((short) getExpectedAnswerLength(), retval, 7, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
app/src/main/java/net/alphadev/usbstorage/DeviceManager.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BulkDevice.java // public interface BulkDevice extends Closeable, Identifiable { // /** // * Transmits a given payload to the device BulkDevice being represented. // * // * @param payload to transfer // * @return the amount actually sent // */ // int write(Transmittable payload); // // /** // * Receives a payload of a given length from the BulkDevice being represented. // * // * @param length of the payload // * @return the payload data // */ // byte[] read(int length); // // /** // * @return true if the connection to the BulkDevice being represented has already been disengaged. // */ // boolean isClosed(); // }
import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import net.alphadev.usbstorage.api.device.BulkDevice;
IntentFilter attachmentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED); BroadcastReceiver mAttachmentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { enumerateDevices(); } }; context.registerReceiver(mAttachmentReceiver, attachmentFilter); IntentFilter detachmentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED); BroadcastReceiver mDetachmentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); unmountRemovedDevices(device); } }; context.registerReceiver(mDetachmentReceiver, detachmentFilter); enumerateDevices(); } private void unmountRemovedDevices(UsbDevice device) { String deviceId = Integer.valueOf(device.getDeviceId()).toString(); mStorageManager.unmount(deviceId); mStorageManager.notifyStorageChanged(); } private void tryMount(UsbDevice device) {
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BulkDevice.java // public interface BulkDevice extends Closeable, Identifiable { // /** // * Transmits a given payload to the device BulkDevice being represented. // * // * @param payload to transfer // * @return the amount actually sent // */ // int write(Transmittable payload); // // /** // * Receives a payload of a given length from the BulkDevice being represented. // * // * @param length of the payload // * @return the payload data // */ // byte[] read(int length); // // /** // * @return true if the connection to the BulkDevice being represented has already been disengaged. // */ // boolean isClosed(); // } // Path: app/src/main/java/net/alphadev/usbstorage/DeviceManager.java import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import net.alphadev.usbstorage.api.device.BulkDevice; IntentFilter attachmentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED); BroadcastReceiver mAttachmentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { enumerateDevices(); } }; context.registerReceiver(mAttachmentReceiver, attachmentFilter); IntentFilter detachmentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED); BroadcastReceiver mDetachmentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); unmountRemovedDevices(device); } }; context.registerReceiver(mDetachmentReceiver, detachmentFilter); enumerateDevices(); } private void unmountRemovedDevices(UsbDevice device) { String deviceId = Integer.valueOf(device.getDeviceId()).toString(); mStorageManager.unmount(deviceId); mStorageManager.notifyStorageChanged(); } private void tryMount(UsbDevice device) {
final BulkDevice usbBulkDevice = UsbBulkDevice.read(mContext, device);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi; /** * @author Jan Seeger <jan@alphadev.net> */ public class CommandBlockWrapper implements ScsiTransferable { private static int tagCounter = 0; private final byte[] cwbData; public CommandBlockWrapper() { cwbData = new byte[0x1f]; // set CBW signature cwbData[0x0] = 'U'; cwbData[0x1] = 'S'; cwbData[0x2] = 'B'; cwbData[0x3] = 'C'; // increase and write tag counter
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi; /** * @author Jan Seeger <jan@alphadev.net> */ public class CommandBlockWrapper implements ScsiTransferable { private static int tagCounter = 0; private final byte[] cwbData; public CommandBlockWrapper() { cwbData = new byte[0x1f]; // set CBW signature cwbData[0x0] = 'U'; cwbData[0x1] = 'S'; cwbData[0x2] = 'B'; cwbData[0x3] = 'C'; // increase and write tag counter
BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN);
alphadev-net/drive-mount
scsi/src/test/java/net/alphadev/usbstorage/test/CommandBlockWrapperTest.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // }
import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
0x24, 0x0, 0x0, 0x0, // transfer length 0x0, // flags 0x0, // lun 0x6, // length 0x1, 0x2, 0x3, 0x4, // payload 1 0x5, 0x6, 0x0, 0x0, // payload 2 0x0, 0x0, 0x0, 0x0, // payload 3 0x0, 0x0, 0x0, 0x0 // payload 4 }; Assert.assertArrayEquals(expected, cbw.asBytes()); } @Test public void checkPayloadSizeCalculation() { byte[] cbwBytes = cbw.asBytes(); byte length = cbwBytes[0xe]; int counter = 0; int lastPos = 0; for (int i = 0xf; i < cbwBytes.length; i++) { if (cbwBytes[i] != 0) { counter++; lastPos = i; } } Assert.assertEquals(length, counter); Assert.assertEquals(15 + length - 1, lastPos); }
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // Path: scsi/src/test/java/net/alphadev/usbstorage/test/CommandBlockWrapperTest.java import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; 0x24, 0x0, 0x0, 0x0, // transfer length 0x0, // flags 0x0, // lun 0x6, // length 0x1, 0x2, 0x3, 0x4, // payload 1 0x5, 0x6, 0x0, 0x0, // payload 2 0x0, 0x0, 0x0, 0x0, // payload 3 0x0, 0x0, 0x0, 0x0 // payload 4 }; Assert.assertArrayEquals(expected, cbw.asBytes()); } @Test public void checkPayloadSizeCalculation() { byte[] cbwBytes = cbw.asBytes(); byte length = cbwBytes[0xe]; int counter = 0; int lastPos = 0; for (int i = 0xf; i < cbwBytes.length; i++) { if (cbwBytes[i] != 0) { counter++; lastPos = i; } } Assert.assertEquals(length, counter); Assert.assertEquals(15 + length - 1, lastPos); }
private static class TransmittableDummy implements ScsiTransferable {
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/RequestSenseResponse.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class RequestSenseResponse { public static final byte LENGTH = 18; /** * False indicates the information field not formatted according to SCSI standard. */ private final boolean mValid; private final boolean mFilemark; private final boolean mEOM; private final boolean mILI; private final boolean mSKSV; private final ResponseCode mResponseCode; private final SenseKey mSenseKey; private final byte mAdditionalSenseLength; private final byte mAdditionalSenseCode; private final byte mAdditionalSenseQualifier; private final byte mFieldReplacableUnitCode; private final int mInformation; private final int mCommandSpecificInformation; /** * This field is only 3 byte long! */ private final int mSenseKeySpecific; public RequestSenseResponse(byte[] answer) { mValid = (answer[0] & 0x80) == 0x80; mResponseCode = determineResponseCode((byte) (answer[0] & 0x7f)); mFilemark = (answer[1] & 0x80) == 0x80; mEOM = (answer[1] & 0x40) == 0x40; mILI = (answer[1] & 0x20) == 0x20; mSenseKey = determineSenseKey((byte) (answer[1] & 0xf));
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/RequestSenseResponse.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class RequestSenseResponse { public static final byte LENGTH = 18; /** * False indicates the information field not formatted according to SCSI standard. */ private final boolean mValid; private final boolean mFilemark; private final boolean mEOM; private final boolean mILI; private final boolean mSKSV; private final ResponseCode mResponseCode; private final SenseKey mSenseKey; private final byte mAdditionalSenseLength; private final byte mAdditionalSenseCode; private final byte mAdditionalSenseQualifier; private final byte mFieldReplacableUnitCode; private final int mInformation; private final int mCommandSpecificInformation; /** * This field is only 3 byte long! */ private final int mSenseKeySpecific; public RequestSenseResponse(byte[] answer) { mValid = (answer[0] & 0x80) == 0x80; mResponseCode = determineResponseCode((byte) (answer[0] & 0x7f)); mFilemark = (answer[1] & 0x80) == 0x80; mEOM = (answer[1] & 0x40) == 0x40; mILI = (answer[1] & 0x20) == 0x20; mSenseKey = determineSenseKey((byte) (answer[1] & 0xf));
mInformation = BitStitching.convertToInt(answer, 3, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Read10.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class Read10 extends ScsiCommand { private static final byte READ10 = 0x28; private long offset; private short transferLength; private int mAnswerLength; @Override
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Read10.java import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class Read10 extends ScsiCommand { private static final byte READ10 = 0x28; private long offset; private short transferLength; private int mAnswerLength; @Override
public CommandBlockWrapper.Direction getDirection() {
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Read10.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class Read10 extends ScsiCommand { private static final byte READ10 = 0x28; private long offset; private short transferLength; private int mAnswerLength; @Override public CommandBlockWrapper.Direction getDirection() { return CommandBlockWrapper.Direction.DEVICE_TO_HOST; } @Override public byte[] asBytes() { final byte[] bytes = new byte[10]; bytes[0] = READ10; // opcode // 1 == flags
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Read10.java import net.alphadev.usbstorage.scsi.CommandBlockWrapper; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ public class Read10 extends ScsiCommand { private static final byte READ10 = 0x28; private long offset; private short transferLength; private int mAnswerLength; @Override public CommandBlockWrapper.Direction getDirection() { return CommandBlockWrapper.Direction.DEVICE_TO_HOST; } @Override public byte[] asBytes() { final byte[] bytes = new byte[10]; bytes[0] = READ10; // opcode // 1 == flags
BitStitching.setBytesFromInt((int) offset, bytes, 2, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandStatusWrapper.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi; /** * @author Jan Seeger <jan@alphadev.net> */ public class CommandStatusWrapper { public static final String USB_STATUS_SIGNATURE = "USBS"; private byte[] mSignature; private int mTag; private int mDataResidue; private byte mStatus; public CommandStatusWrapper(byte[] data) { if (data.length != 13) { throw new IllegalArgumentException("CSW always has a length of 13 bytes!"); } mSignature = new byte[4]; mSignature[0x0] = data[0x0]; mSignature[0x1] = data[0x1]; mSignature[0x2] = data[0x2]; mSignature[0x3] = data[0x3]; if (!USB_STATUS_SIGNATURE.equals(getSignature())) {
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandStatusWrapper.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi; /** * @author Jan Seeger <jan@alphadev.net> */ public class CommandStatusWrapper { public static final String USB_STATUS_SIGNATURE = "USBS"; private byte[] mSignature; private int mTag; private int mDataResidue; private byte mStatus; public CommandStatusWrapper(byte[] data) { if (data.length != 13) { throw new IllegalArgumentException("CSW always has a length of 13 bytes!"); } mSignature = new byte[4]; mSignature[0x0] = data[0x0]; mSignature[0x1] = data[0x1]; mSignature[0x2] = data[0x2]; mSignature[0x3] = data[0x3]; if (!USB_STATUS_SIGNATURE.equals(getSignature())) {
System.out.println(BitStitching.convertBytesToHex(data));
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadCapacity.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadCapacity extends ScsiCommand { public static final byte READ_CAPACITY = 0x25; private int mLogicalBlockAddress; private byte mControl; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_CAPACITY; // opcode // retval[1] is reserved
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadCapacity.java import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadCapacity extends ScsiCommand { public static final byte READ_CAPACITY = 0x25; private int mLogicalBlockAddress; private byte mControl; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_CAPACITY; // opcode // retval[1] is reserved
BitStitching.setBytesFromInt(mLogicalBlockAddress, retval, 2, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadCapacity.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadCapacity extends ScsiCommand { public static final byte READ_CAPACITY = 0x25; private int mLogicalBlockAddress; private byte mControl; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_CAPACITY; // opcode // retval[1] is reserved BitStitching.setBytesFromInt(mLogicalBlockAddress, retval, 2, ByteOrder.BIG_ENDIAN); // retval[6-8] is reserved retval[9] = mControl; return retval; } @Override public int getExpectedAnswerLength() {
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadCapacityResponse.java // public class ReadCapacityResponse { // public static final int LENGTH = 8; // // private final int mBlockSize; // private final int mNumberOfBlocks; // // public ReadCapacityResponse(byte[] answer) { // mNumberOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN); // mBlockSize = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // } // // public int getBlockSize() { // return mBlockSize; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ReadCapacity.java import net.alphadev.usbstorage.scsi.answer.ReadCapacityResponse; import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadCapacity extends ScsiCommand { public static final byte READ_CAPACITY = 0x25; private int mLogicalBlockAddress; private byte mControl; @Override public byte[] asBytes() { byte[] retval = new byte[10]; retval[0] = READ_CAPACITY; // opcode // retval[1] is reserved BitStitching.setBytesFromInt(mLogicalBlockAddress, retval, 2, ByteOrder.BIG_ENDIAN); // retval[6-8] is reserved retval[9] = mControl; return retval; } @Override public int getExpectedAnswerLength() {
return ReadCapacityResponse.LENGTH;
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Inquiry.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/StandardInquiryAnswer.java // @SuppressWarnings("unused") // public class StandardInquiryAnswer { // public static final byte LENGTH = 0x24; // private final byte mResponseDataFormat; // private final boolean mSccs; // private final short mVersionDescriptor1; // private final short mVersionDescriptor2; // private final short mVersionDescriptor3; // private byte mPeripheralQualifier; // private byte mPeripheralDeviceType; // private boolean mRemovable; // private boolean mAerc; // private boolean mNormAca; // /** // * Hierarchical Addressing Support // */ // private boolean mHiSup; // private byte mAdditionalLength; // private String mVendorId; // private String mProductId; // private String mRevisionId; // /** // * Version 4 == SPC-2 // */ // private byte mVersion; // // public StandardInquiryAnswer(byte[] answer) { // if (answer.length != LENGTH) { // throw new IllegalArgumentException("Inquiry answer has invalid length!"); // } // // mPeripheralDeviceType = (byte) (answer[0] & 0xe0); // mPeripheralQualifier = (byte) (answer[0] & 0x1f); // mRemovable = answer[1] == (byte) 0x80; // mVersion = answer[2]; // mAerc = answer[3] == (byte) 0x80; // mNormAca = answer[3] == (byte) 0x20; // mHiSup = answer[3] == (byte) 0x10; // mAdditionalLength = answer[4]; // mRemovable = answer[5] == (byte) 0x80; // mVendorId = BitStitching.bytesToString(answer, 8, 8); // mProductId = BitStitching.bytesToString(answer, 16, 16); // mRevisionId = BitStitching.bytesToString(answer, 32, 4); // mVersionDescriptor1 = 0; // mVersionDescriptor2 = 0; // mVersionDescriptor3 = 0; // mResponseDataFormat = 0; // mSccs = false; // } // // public byte getAdditionalLength() { // return mAdditionalLength; // } // // public byte getPeripheralQualifier() { // return mPeripheralQualifier; // } // // public byte getPeripheralDeviceType() { // return mPeripheralDeviceType; // } // // public boolean isRemovable() { // return mRemovable; // } // // public boolean isAerc() { // return mAerc; // } // // public boolean isNormAca() { // return mNormAca; // } // // public boolean isHiSup() { // return mHiSup; // } // // public byte getResponseDataFormat() { // return mResponseDataFormat; // } // // public boolean isSccs() { // return mSccs; // } // // public String getVendorId() { // return mVendorId; // } // // public String getProductId() { // return mProductId; // } // // public String getRevisionId() { // return mRevisionId; // } // // public short getVersionDescriptor1() { // return mVersionDescriptor1; // } // // public short getVersionDescriptor2() { // return mVersionDescriptor2; // } // // public short getVersionDescriptor3() { // return mVersionDescriptor3; // } // // public byte getVersion() { // return mVersion; // } // }
import net.alphadev.usbstorage.scsi.answer.StandardInquiryAnswer;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class Inquiry extends ScsiCommand { public static final byte INQUIRY = 0x12; private boolean mCmdDt; private boolean mEvpd; @Override public byte[] asBytes() { byte[] buffer = new byte[6]; buffer[0] = INQUIRY; // opcode if (mCmdDt) { buffer[1] += 2; } if (mEvpd) { buffer[1] += 1; }
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/StandardInquiryAnswer.java // @SuppressWarnings("unused") // public class StandardInquiryAnswer { // public static final byte LENGTH = 0x24; // private final byte mResponseDataFormat; // private final boolean mSccs; // private final short mVersionDescriptor1; // private final short mVersionDescriptor2; // private final short mVersionDescriptor3; // private byte mPeripheralQualifier; // private byte mPeripheralDeviceType; // private boolean mRemovable; // private boolean mAerc; // private boolean mNormAca; // /** // * Hierarchical Addressing Support // */ // private boolean mHiSup; // private byte mAdditionalLength; // private String mVendorId; // private String mProductId; // private String mRevisionId; // /** // * Version 4 == SPC-2 // */ // private byte mVersion; // // public StandardInquiryAnswer(byte[] answer) { // if (answer.length != LENGTH) { // throw new IllegalArgumentException("Inquiry answer has invalid length!"); // } // // mPeripheralDeviceType = (byte) (answer[0] & 0xe0); // mPeripheralQualifier = (byte) (answer[0] & 0x1f); // mRemovable = answer[1] == (byte) 0x80; // mVersion = answer[2]; // mAerc = answer[3] == (byte) 0x80; // mNormAca = answer[3] == (byte) 0x20; // mHiSup = answer[3] == (byte) 0x10; // mAdditionalLength = answer[4]; // mRemovable = answer[5] == (byte) 0x80; // mVendorId = BitStitching.bytesToString(answer, 8, 8); // mProductId = BitStitching.bytesToString(answer, 16, 16); // mRevisionId = BitStitching.bytesToString(answer, 32, 4); // mVersionDescriptor1 = 0; // mVersionDescriptor2 = 0; // mVersionDescriptor3 = 0; // mResponseDataFormat = 0; // mSccs = false; // } // // public byte getAdditionalLength() { // return mAdditionalLength; // } // // public byte getPeripheralQualifier() { // return mPeripheralQualifier; // } // // public byte getPeripheralDeviceType() { // return mPeripheralDeviceType; // } // // public boolean isRemovable() { // return mRemovable; // } // // public boolean isAerc() { // return mAerc; // } // // public boolean isNormAca() { // return mNormAca; // } // // public boolean isHiSup() { // return mHiSup; // } // // public byte getResponseDataFormat() { // return mResponseDataFormat; // } // // public boolean isSccs() { // return mSccs; // } // // public String getVendorId() { // return mVendorId; // } // // public String getProductId() { // return mProductId; // } // // public String getRevisionId() { // return mRevisionId; // } // // public short getVersionDescriptor1() { // return mVersionDescriptor1; // } // // public short getVersionDescriptor2() { // return mVersionDescriptor2; // } // // public short getVersionDescriptor3() { // return mVersionDescriptor3; // } // // public byte getVersion() { // return mVersion; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/Inquiry.java import net.alphadev.usbstorage.scsi.answer.StandardInquiryAnswer; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class Inquiry extends ScsiCommand { public static final byte INQUIRY = 0x12; private boolean mCmdDt; private boolean mEvpd; @Override public byte[] asBytes() { byte[] buffer = new byte[6]; buffer[0] = INQUIRY; // opcode if (mCmdDt) { buffer[1] += 2; } if (mEvpd) { buffer[1] += 1; }
buffer[4] = StandardInquiryAnswer.LENGTH; // LENGTH
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesEntry.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadFormatCapacitiesEntry { public static final int LENGTH = 8; private final int mNumOfBlocks; private final FormatType mFormatType; private int mTypeDependentParameter; public ReadFormatCapacitiesEntry(byte[] answer) {
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesEntry.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.answer; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class ReadFormatCapacitiesEntry { public static final int LENGTH = 8; private final int mNumOfBlocks; private final FormatType mFormatType; private int mTypeDependentParameter; public ReadFormatCapacitiesEntry(byte[] answer) {
mNumOfBlocks = BitStitching.convertToInt(answer, 0, ByteOrder.BIG_ENDIAN);
alphadev-net/drive-mount
scsi/src/test/java/net/alphadev/usbstorage/test/BitStitchingEndiannessTest.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * Test correct handling of endianness in BitStitching util class. * * @author Jan Seeger <jan@alphadev.net> * @see <a href="http://de.wikipedia.org/wiki/Byte-Reihenfolge#Beispiel:_Speicherung_einer_Integer-Zahl_von_32_Bit_in_4_Bytes">http://de.wikipedia.org/wiki/Byte-Reihenfolge#Beispiel:_Speicherung_einer_Integer-Zahl_von_32_Bit_in_4_Bytes</a> */ public class BitStitchingEndiannessTest { /** * Convert little endian byte[] to big endian number (java default). */ @Test public void convertsProperlyToLittleEndianByteArray() { byte[] expected = new byte[]{0x4d, 0x3c, 0x2b, 0x1a}; int input = 439041101; byte[] result = new byte[4];
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/test/java/net/alphadev/usbstorage/test/BitStitchingEndiannessTest.java import net.alphadev.usbstorage.util.BitStitching; import org.junit.Assert; import org.junit.Test; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * Test correct handling of endianness in BitStitching util class. * * @author Jan Seeger <jan@alphadev.net> * @see <a href="http://de.wikipedia.org/wiki/Byte-Reihenfolge#Beispiel:_Speicherung_einer_Integer-Zahl_von_32_Bit_in_4_Bytes">http://de.wikipedia.org/wiki/Byte-Reihenfolge#Beispiel:_Speicherung_einer_Integer-Zahl_von_32_Bit_in_4_Bytes</a> */ public class BitStitchingEndiannessTest { /** * Convert little endian byte[] to big endian number (java default). */ @Test public void convertsProperlyToLittleEndianByteArray() { byte[] expected = new byte[]{0x4d, 0x3c, 0x2b, 0x1a}; int input = 439041101; byte[] result = new byte[4];
BitStitching.setBytesFromInt(input, result, 0, ByteOrder.LITTLE_ENDIAN);
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/StandardInquiryAnswer.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching;
private boolean mRemovable; private boolean mAerc; private boolean mNormAca; /** * Hierarchical Addressing Support */ private boolean mHiSup; private byte mAdditionalLength; private String mVendorId; private String mProductId; private String mRevisionId; /** * Version 4 == SPC-2 */ private byte mVersion; public StandardInquiryAnswer(byte[] answer) { if (answer.length != LENGTH) { throw new IllegalArgumentException("Inquiry answer has invalid length!"); } mPeripheralDeviceType = (byte) (answer[0] & 0xe0); mPeripheralQualifier = (byte) (answer[0] & 0x1f); mRemovable = answer[1] == (byte) 0x80; mVersion = answer[2]; mAerc = answer[3] == (byte) 0x80; mNormAca = answer[3] == (byte) 0x20; mHiSup = answer[3] == (byte) 0x10; mAdditionalLength = answer[4]; mRemovable = answer[5] == (byte) 0x80;
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/StandardInquiryAnswer.java import net.alphadev.usbstorage.util.BitStitching; private boolean mRemovable; private boolean mAerc; private boolean mNormAca; /** * Hierarchical Addressing Support */ private boolean mHiSup; private byte mAdditionalLength; private String mVendorId; private String mProductId; private String mRevisionId; /** * Version 4 == SPC-2 */ private byte mVersion; public StandardInquiryAnswer(byte[] answer) { if (answer.length != LENGTH) { throw new IllegalArgumentException("Inquiry answer has invalid length!"); } mPeripheralDeviceType = (byte) (answer[0] & 0xe0); mPeripheralQualifier = (byte) (answer[0] & 0x1f); mRemovable = answer[1] == (byte) 0x80; mVersion = answer[2]; mAerc = answer[3] == (byte) 0x80; mNormAca = answer[3] == (byte) 0x20; mHiSup = answer[3] == (byte) 0x10; mAdditionalLength = answer[4]; mRemovable = answer[5] == (byte) 0x80;
mVendorId = BitStitching.bytesToString(answer, 8, 8);
alphadev-net/drive-mount
api/src/test/java/net/alphadev/usbstorage/api/tests/PathTest.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // }
import net.alphadev.usbstorage.api.filesystem.Path; import org.junit.Assert; import org.junit.Test; import java.util.Iterator;
/** * Copyright © 2014-2015 Jan Seeger * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 net.alphadev.usbstorage.api.tests; /** * @author Jan Seeger <jan@alphadev.net> */ public class PathTest { @Test public void basicHasNoParentsTest() {
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // } // Path: api/src/test/java/net/alphadev/usbstorage/api/tests/PathTest.java import net.alphadev.usbstorage.api.filesystem.Path; import org.junit.Assert; import org.junit.Test; import java.util.Iterator; /** * Copyright © 2014-2015 Jan Seeger * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 net.alphadev.usbstorage.api.tests; /** * @author Jan Seeger <jan@alphadev.net> */ public class PathTest { @Test public void basicHasNoParentsTest() {
Path instance = new Path("driveId/");
alphadev-net/drive-mount
fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // }
import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.fat32wrapper; /** * @author Jan Seeger <jan@alphadev.net> */ public class Fat32Provider implements FileSystemProvider { private final FatFileSystem fs; public Fat32Provider(FatFileSystem fs) { this.fs = fs; } @Override
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // } // Path: fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.fat32wrapper; /** * @author Jan Seeger <jan@alphadev.net> */ public class Fat32Provider implements FileSystemProvider { private final FatFileSystem fs; public Fat32Provider(FatFileSystem fs) { this.fs = fs; } @Override
public boolean isDirectory(Path path) {
alphadev-net/drive-mount
fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // }
import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry;
final FatLfnDirectoryEntry file = getEntry(path); return file != null && file.isDirectory(); } @Override public Iterable<Path> getEntries(Path path) { final List<Path> entries = new ArrayList<>(); FatLfnDirectory directory; if (path.isRoot()) { directory = fs.getRoot(); } else { directory = getDirectoryOrNull(getEntry(path)); } if (directory != null) { for (FsDirectoryEntry entry : directory) { if (entry.getName().equals(".") || entry.getName().equals("..")) { continue; } Path file = Path.createWithAppended(path, entry.getName()); entries.add(file); } } return entries; } @Override
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // } // Path: fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry; final FatLfnDirectoryEntry file = getEntry(path); return file != null && file.isDirectory(); } @Override public Iterable<Path> getEntries(Path path) { final List<Path> entries = new ArrayList<>(); FatLfnDirectory directory; if (path.isRoot()) { directory = fs.getRoot(); } else { directory = getDirectoryOrNull(getEntry(path)); } if (directory != null) { for (FsDirectoryEntry entry : directory) { if (entry.getName().equals(".") || entry.getName().equals("..")) { continue; } Path file = Path.createWithAppended(path, entry.getName()); entries.add(file); } } return entries; } @Override
public Object getAttribute(Path path, FileAttribute attr) {
alphadev-net/drive-mount
fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // }
import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry;
public Object getAttribute(Path path, FileAttribute attr) { switch (attr) { case FILESIZE: return getFileSize(path); case LAST_MODIFIED: return getLastModified(path); default: return null; } } private long getFileSize(Path path) { final FatFile file = getFileOrNull(path); return file != null ? file.getLength() : 0; } private long getLastModified(Path path) { final FatLfnDirectoryEntry entry = getEntry(path); if (entry != null && entry.isFile()) { try { return entry.getLastModified(); } catch (IOException e) { return 0; } } return 0; } @Override
// Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileAttribute.java // public enum FileAttribute { // FILESIZE, // LAST_MODIFIED // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileHandle.java // public interface FileHandle { // InputStream readDocument(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/FileSystemProvider.java // public interface FileSystemProvider { // /** // * Returs true if, and only if, the item represented by the given Path is a directory. // * // * @param path Path to check // * @return true if is directory // */ // boolean isDirectory(Path path); // // /** // * Returns list of Paths (sub entries) for a given Path or an empty list otherwise. // * // * @param path path Path to look for sub entries // * @return List of Paths // */ // Iterable<Path> getEntries(Path path); // // /** // * Returns the requested File Attribute or null if not applicable. // * // * @param path Path to get the Attribute for // * @param attr Type of Attribute accortidng to FileAttribute // * @return Attribute value or null // */ // Object getAttribute(Path path, FileAttribute attr); // // FileHandle openDocument(Path path); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/filesystem/Path.java // public final class Path { // private final List<String> paths; // // public Path(String path) { // this(Arrays.asList(path.split("/"))); // } // // private Path(List<String> list) { // this.paths = list; // } // // public static Path createWithAppended(Path path, String... appendToPath) { // final List<String> paths = new ArrayList<>(path.paths); // for (String appendix : appendToPath) { // if (appendix.indexOf('/') != -1) { // paths.addAll(Arrays.asList(appendix.split("/"))); // } else { // paths.add(appendix); // } // } // return new Path(paths); // } // // /** // * Returns parent. // * // * @return parent path or null // */ // public Path getParent() { // if (paths.size() < 3) { // return null; // } // // List<String> parentPaths = paths.subList(0, paths.size() - 1); // return new Path(parentPaths); // } // // public String getName() { // if (paths.size() < 2) { // return null; // } // // return paths.get(paths.size() - 1); // } // // public String getDeviceId() { // if (paths.get(0).isEmpty()) { // return null; // } // // return paths.get(0); // } // // public final Iterable<String> getIterator() { // return paths.subList(1, paths.size()); // } // // public String toAbsolute() { // StringBuilder sb = new StringBuilder(); // boolean firstTime = true; // // for (String token : paths) { // if (firstTime) { // firstTime = false; // } else { // sb.append('/'); // } // sb.append(token); // } // // return sb.toString(); // } // // public boolean isRoot() { // return paths.size() == 1; // } // } // Path: fat32/src/main/java/net/alphadev/fat32wrapper/Fat32Provider.java import net.alphadev.usbstorage.api.filesystem.FileAttribute; import net.alphadev.usbstorage.api.filesystem.FileHandle; import net.alphadev.usbstorage.api.filesystem.FileSystemProvider; import net.alphadev.usbstorage.api.filesystem.Path; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import de.waldheinz.fs.FsDirectoryEntry; import de.waldheinz.fs.fat.FatFile; import de.waldheinz.fs.fat.FatFileSystem; import de.waldheinz.fs.fat.FatLfnDirectory; import de.waldheinz.fs.fat.FatLfnDirectoryEntry; public Object getAttribute(Path path, FileAttribute attr) { switch (attr) { case FILESIZE: return getFileSize(path); case LAST_MODIFIED: return getLastModified(path); default: return null; } } private long getFileSize(Path path) { final FatFile file = getFileOrNull(path); return file != null ? file.getLength() : 0; } private long getLastModified(Path path) { final FatLfnDirectoryEntry entry = getEntry(path); if (entry != null && entry.isFile()) { try { return entry.getLastModified(); } catch (IOException e) { return 0; } } return 0; } @Override
public FileHandle openDocument(Path path) {
alphadev-net/drive-mount
scsi/src/test/java/net/alphadev/usbstorage/test/ReadFormatCapacitiesTest.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesHeader.java // @SuppressWarnings("unused") // public class ReadFormatCapacitiesHeader { // public static final int LENGTH = 12; // // private byte mCapacityListLength; // private int mNumberOfBlocks; // private DescriptorType mDescriptorType; // private int mBlockLength; // // public ReadFormatCapacitiesHeader(byte[] answer) { // /** first three bits are reserved **/ // mCapacityListLength = answer[3]; // // boolean hasValidNumOfEntries = mCapacityListLength % 8 == 0; // int numOfEntries = mCapacityListLength / 8; // if (!hasValidNumOfEntries || numOfEntries <= 0 || numOfEntries >= 256) { // throw new IllegalArgumentException("Invalid CapacityListLength!"); // } // // mCapacityListLength = (byte) numOfEntries; // mNumberOfBlocks = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // // mDescriptorType = getDescriptorType(answer[5]); // // byte[] tempBlockLength = new byte[]{ // 0, answer[9], answer[10], answer[11], // }; // // mBlockLength = BitStitching.convertToInt(tempBlockLength, 0, ByteOrder.BIG_ENDIAN); // } // // /** // * Extracts Bitflags from a given byte according to the following schema: // * <p/> // * 00b = Reserved. // * 01b = Unformatted Media. // * 10b = Formatted Media. // * 11b = No Media Present. // * // * @param b byte holding the flags // */ // private DescriptorType getDescriptorType(byte b) { // switch (b) { // case 1: // return DescriptorType.UNFORMATTED_MEDIA; // case 2: // return DescriptorType.FORMATTED_MEDIA; // case 3: // return DescriptorType.NO_MEDIA_PRESENT; // default: // return DescriptorType.RESERVED; // } // } // // public int getCapacityEntryCount() { // return mCapacityListLength; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // // public DescriptorType getDescriptorTypes() { // return mDescriptorType; // } // // public int getBlockLength() { // return mBlockLength; // } // // public static enum DescriptorType { // RESERVED, // UNFORMATTED_MEDIA, // FORMATTED_MEDIA, // NO_MEDIA_PRESENT // } // }
import net.alphadev.usbstorage.scsi.answer.ReadFormatCapacitiesHeader; import org.junit.Test;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadFormatCapacitiesTest { @Test public void doesNotComplainOnValidValues() {
// Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/answer/ReadFormatCapacitiesHeader.java // @SuppressWarnings("unused") // public class ReadFormatCapacitiesHeader { // public static final int LENGTH = 12; // // private byte mCapacityListLength; // private int mNumberOfBlocks; // private DescriptorType mDescriptorType; // private int mBlockLength; // // public ReadFormatCapacitiesHeader(byte[] answer) { // /** first three bits are reserved **/ // mCapacityListLength = answer[3]; // // boolean hasValidNumOfEntries = mCapacityListLength % 8 == 0; // int numOfEntries = mCapacityListLength / 8; // if (!hasValidNumOfEntries || numOfEntries <= 0 || numOfEntries >= 256) { // throw new IllegalArgumentException("Invalid CapacityListLength!"); // } // // mCapacityListLength = (byte) numOfEntries; // mNumberOfBlocks = BitStitching.convertToInt(answer, 4, ByteOrder.BIG_ENDIAN); // // mDescriptorType = getDescriptorType(answer[5]); // // byte[] tempBlockLength = new byte[]{ // 0, answer[9], answer[10], answer[11], // }; // // mBlockLength = BitStitching.convertToInt(tempBlockLength, 0, ByteOrder.BIG_ENDIAN); // } // // /** // * Extracts Bitflags from a given byte according to the following schema: // * <p/> // * 00b = Reserved. // * 01b = Unformatted Media. // * 10b = Formatted Media. // * 11b = No Media Present. // * // * @param b byte holding the flags // */ // private DescriptorType getDescriptorType(byte b) { // switch (b) { // case 1: // return DescriptorType.UNFORMATTED_MEDIA; // case 2: // return DescriptorType.FORMATTED_MEDIA; // case 3: // return DescriptorType.NO_MEDIA_PRESENT; // default: // return DescriptorType.RESERVED; // } // } // // public int getCapacityEntryCount() { // return mCapacityListLength; // } // // public int getNumberOfBlocks() { // return mNumberOfBlocks; // } // // public DescriptorType getDescriptorTypes() { // return mDescriptorType; // } // // public int getBlockLength() { // return mBlockLength; // } // // public static enum DescriptorType { // RESERVED, // UNFORMATTED_MEDIA, // FORMATTED_MEDIA, // NO_MEDIA_PRESENT // } // } // Path: scsi/src/test/java/net/alphadev/usbstorage/test/ReadFormatCapacitiesTest.java import net.alphadev.usbstorage.scsi.answer.ReadFormatCapacitiesHeader; import org.junit.Test; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.test; /** * @author Jan Seeger <jan@alphadev.net> */ public class ReadFormatCapacitiesTest { @Test public void doesNotComplainOnValidValues() {
new ReadFormatCapacitiesHeader(new byte[]{
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/partition/PartitionParameters.java
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.partition; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class PartitionParameters { private final byte mPartitionOffset; private final boolean mBootIndicator; private final FileSystemDescriptor mDescriptor; private final HeadSectorCylinder mPartitionStart; private final HeadSectorCylinder mPartitionEnd; private final int mLogicalStart; private final int mNumberOfSectors; public PartitionParameters(byte[] data, byte offset) { mPartitionOffset = offset; mBootIndicator = data[0x0] == 0x80; mPartitionStart = new HeadSectorCylinder(data, 0x1); mDescriptor = FileSystemDescriptor.parse(data[4]); mPartitionEnd = new HeadSectorCylinder(data, 0x5);
// Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/partition/PartitionParameters.java import net.alphadev.usbstorage.util.BitStitching; import java.nio.ByteOrder; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.partition; /** * @author Jan Seeger <jan@alphadev.net> */ @SuppressWarnings("unused") public class PartitionParameters { private final byte mPartitionOffset; private final boolean mBootIndicator; private final FileSystemDescriptor mDescriptor; private final HeadSectorCylinder mPartitionStart; private final HeadSectorCylinder mPartitionEnd; private final int mLogicalStart; private final int mNumberOfSectors; public PartitionParameters(byte[] data, byte offset) { mPartitionOffset = offset; mBootIndicator = data[0x0] == 0x80; mPartitionStart = new HeadSectorCylinder(data, 0x1); mDescriptor = FileSystemDescriptor.parse(data[4]); mPartitionEnd = new HeadSectorCylinder(data, 0x5);
mLogicalStart = BitStitching.convertToInt(data, 0x8, ByteOrder.LITTLE_ENDIAN);
alphadev-net/drive-mount
app/src/main/java/net/alphadev/usbstorage/UsbBulkDevice.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BulkDevice.java // public interface BulkDevice extends Closeable, Identifiable { // /** // * Transmits a given payload to the device BulkDevice being represented. // * // * @param payload to transfer // * @return the amount actually sent // */ // int write(Transmittable payload); // // /** // * Receives a payload of a given length from the BulkDevice being represented. // * // * @param length of the payload // * @return the payload data // */ // byte[] read(int length); // // /** // * @return true if the connection to the BulkDevice being represented has already been disengaged. // */ // boolean isClosed(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/Transmittable.java // public interface Transmittable { // /** // * Returns the payload data as byte array. // * // * @return payload data // */ // byte[] asBytes(); // }
import android.content.Context; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbManager; import net.alphadev.usbstorage.api.device.BulkDevice; import net.alphadev.usbstorage.api.scsi.Transmittable; import java.io.IOException;
private static UsbEndpoint findUsableEndpoints(UsbInterface usbInterface, int direction) { for (int i = 0; i < usbInterface.getEndpointCount(); i++) { UsbEndpoint endpointProbe = usbInterface.getEndpoint(i); if (endpointProbe.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (endpointProbe.getDirection() == direction) { return endpointProbe; } } } return null; } private static UsbInterface findUsableInterface(UsbDevice device) { for (int i = 0; i < device.getInterfaceCount(); i++) { UsbInterface interfaceProbe = device.getInterface(i); if (interfaceProbe.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE) { if (interfaceProbe.getInterfaceSubclass() == 0x6) { if (interfaceProbe.getInterfaceProtocol() == 0x50) { return device.getInterface(i); } } } } return null; } @Override
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BulkDevice.java // public interface BulkDevice extends Closeable, Identifiable { // /** // * Transmits a given payload to the device BulkDevice being represented. // * // * @param payload to transfer // * @return the amount actually sent // */ // int write(Transmittable payload); // // /** // * Receives a payload of a given length from the BulkDevice being represented. // * // * @param length of the payload // * @return the payload data // */ // byte[] read(int length); // // /** // * @return true if the connection to the BulkDevice being represented has already been disengaged. // */ // boolean isClosed(); // } // // Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/Transmittable.java // public interface Transmittable { // /** // * Returns the payload data as byte array. // * // * @return payload data // */ // byte[] asBytes(); // } // Path: app/src/main/java/net/alphadev/usbstorage/UsbBulkDevice.java import android.content.Context; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbManager; import net.alphadev.usbstorage.api.device.BulkDevice; import net.alphadev.usbstorage.api.scsi.Transmittable; import java.io.IOException; private static UsbEndpoint findUsableEndpoints(UsbInterface usbInterface, int direction) { for (int i = 0; i < usbInterface.getEndpointCount(); i++) { UsbEndpoint endpointProbe = usbInterface.getEndpoint(i); if (endpointProbe.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (endpointProbe.getDirection() == direction) { return endpointProbe; } } } return null; } private static UsbInterface findUsableInterface(UsbDevice device) { for (int i = 0; i < device.getInterfaceCount(); i++) { UsbInterface interfaceProbe = device.getInterface(i); if (interfaceProbe.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE) { if (interfaceProbe.getInterfaceSubclass() == 0x6) { if (interfaceProbe.getInterfaceProtocol() == 0x50) { return device.getInterface(i); } } } } return null; } @Override
public int write(Transmittable command) {
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ScsiCommand.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // }
import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.scsi.CommandBlockWrapper;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * Class that communicates using SCSI Transparent Command Set as specified by: * http://www.13thmonkey.org/documentation/SCSI/spc2r20.pdf * * @author Jan Seeger <jan@alphadev.net> */ public abstract class ScsiCommand implements ScsiTransferable { @SuppressWarnings("SameReturnValue")
// Path: api/src/main/java/net/alphadev/usbstorage/api/scsi/ScsiTransferable.java // public interface ScsiTransferable extends Transmittable { // int getExpectedAnswerLength(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/CommandBlockWrapper.java // public class CommandBlockWrapper implements ScsiTransferable { // private static int tagCounter = 0; // private final byte[] cwbData; // // public CommandBlockWrapper() { // cwbData = new byte[0x1f]; // // // set CBW signature // cwbData[0x0] = 'U'; // cwbData[0x1] = 'S'; // cwbData[0x2] = 'B'; // cwbData[0x3] = 'C'; // // // increase and write tag counter // BitStitching.setBytesFromInt(++tagCounter, cwbData, 0x4, ByteOrder.LITTLE_ENDIAN); // } // // public void setFlags(Direction directionFlags) { // cwbData[0xc] = (byte) (directionFlags == Direction.DEVICE_TO_HOST ? 128 : 0); // } // // public void setLun(byte lun) { // cwbData[0xd] = lun; // } // // public void setCommand(ScsiTransferable command) { // byte[] cmdBlock = command.asBytes(); // // if (cmdBlock.length != 6 && cmdBlock.length != 10 && // cmdBlock.length != 12 && cmdBlock.length != 16) { // throw new IllegalArgumentException("command has invalid size!"); // } // // int cmdOffset = 0xf; // System.arraycopy(cmdBlock, 0, cwbData, cmdOffset, cmdBlock.length); // // cwbData[0xe] = (byte) cmdBlock.length; // BitStitching.setBytesFromInt(command.getExpectedAnswerLength(), cwbData, 0x8, ByteOrder.LITTLE_ENDIAN); // } // // public byte[] asBytes() { // return cwbData.clone(); // } // // @Override // public int getExpectedAnswerLength() { // return 0; // } // // public enum Direction { // HOST_TO_DEVICE, // DEVICE_TO_HOST // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/scsi/command/ScsiCommand.java import net.alphadev.usbstorage.api.scsi.ScsiTransferable; import net.alphadev.usbstorage.scsi.CommandBlockWrapper; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.scsi.command; /** * Class that communicates using SCSI Transparent Command Set as specified by: * http://www.13thmonkey.org/documentation/SCSI/spc2r20.pdf * * @author Jan Seeger <jan@alphadev.net> */ public abstract class ScsiCommand implements ScsiTransferable { @SuppressWarnings("SameReturnValue")
public CommandBlockWrapper.Direction getDirection() {
alphadev-net/drive-mount
scsi/src/main/java/net/alphadev/usbstorage/partition/MasterBootRecord.java
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BlockDevice.java // public interface BlockDevice extends Identifiable, Closeable { // /** // * Gets the total length of this device in bytes. // * // * @return the total number of bytes on this device // * @throws java.io.IOException on error getting the size of this device // */ // public abstract long getSize() throws IOException; // // /** // * Read a block of data from this device. // * // * @param devOffset the byte offset where to read the data from // * @param dest the destination buffer where to store the data read // * @throws IOException on read error // */ // public abstract void read(long devOffset, ByteBuffer dest) // throws IOException; // // /** // * Writes a block of data to this device. // * // * @param devOffset the byte offset where to store the data // * @param src the source {@code ByteBuffer} to write to the device // * @throws IOException on write error // * @throws IllegalArgumentException if the {@code devOffset} is negative // * or the write would go beyond the end of the device // * @see #isReadOnly() // */ // public abstract void write(long devOffset, ByteBuffer src) // throws IOException, // IllegalArgumentException; // // /** // * Flushes data in caches to the actual storage. // * // * @throws IOException on write error // */ // public abstract void flush() throws IOException; // // /** // * Returns the size of a sector on this device. // * // * @return the sector size in bytes // * @throws IOException on error determining the sector size // */ // public int getSectorSize() throws IOException; // // /** // * Closes this {@code BlockDevice}. No methods of this device may be // * accesses after this method was called. // * // * @throws IOException on error closing this device // * @see #isClosed() // */ // public void close() throws IOException; // // /** // * Checks if this device was already closed. No methods may be called // * on a closed device (except this method). // * // * @return if this device is closed // */ // public boolean isClosed(); // // /** // * Checks if this {@code BlockDevice} is read-only. // * // * @return if this {@code BlockDevice} is read-only // */ // public boolean isReadOnly(); // // void initialize(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // }
import net.alphadev.usbstorage.api.device.BlockDevice; import net.alphadev.usbstorage.util.BitStitching; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashSet;
/** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.partition; /** * @author Jan Seeger <jan@alphadev.net> */ public class MasterBootRecord { private static final int SIGNATURE_OFFSET = 0x01FE; private static final int PARTITION_DATA_OFFSET = 0x1BE; private static final int PARTITION_DATA_LENGTH = 16; private final HashSet<Partition> mPartitions;
// Path: api/src/main/java/net/alphadev/usbstorage/api/device/BlockDevice.java // public interface BlockDevice extends Identifiable, Closeable { // /** // * Gets the total length of this device in bytes. // * // * @return the total number of bytes on this device // * @throws java.io.IOException on error getting the size of this device // */ // public abstract long getSize() throws IOException; // // /** // * Read a block of data from this device. // * // * @param devOffset the byte offset where to read the data from // * @param dest the destination buffer where to store the data read // * @throws IOException on read error // */ // public abstract void read(long devOffset, ByteBuffer dest) // throws IOException; // // /** // * Writes a block of data to this device. // * // * @param devOffset the byte offset where to store the data // * @param src the source {@code ByteBuffer} to write to the device // * @throws IOException on write error // * @throws IllegalArgumentException if the {@code devOffset} is negative // * or the write would go beyond the end of the device // * @see #isReadOnly() // */ // public abstract void write(long devOffset, ByteBuffer src) // throws IOException, // IllegalArgumentException; // // /** // * Flushes data in caches to the actual storage. // * // * @throws IOException on write error // */ // public abstract void flush() throws IOException; // // /** // * Returns the size of a sector on this device. // * // * @return the sector size in bytes // * @throws IOException on error determining the sector size // */ // public int getSectorSize() throws IOException; // // /** // * Closes this {@code BlockDevice}. No methods of this device may be // * accesses after this method was called. // * // * @throws IOException on error closing this device // * @see #isClosed() // */ // public void close() throws IOException; // // /** // * Checks if this device was already closed. No methods may be called // * on a closed device (except this method). // * // * @return if this device is closed // */ // public boolean isClosed(); // // /** // * Checks if this {@code BlockDevice} is read-only. // * // * @return if this {@code BlockDevice} is read-only // */ // public boolean isReadOnly(); // // void initialize(); // } // // Path: scsi/src/main/java/net/alphadev/usbstorage/util/BitStitching.java // @SuppressWarnings("unused") // public final class BitStitching { // public static int convertToInt(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.put(byteArray, offset, 4); // b.rewind(); // return b.getInt(); // } // // public static void setBytesFromInt(int integer, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(4); // b.order(order); // b.putInt(integer); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 4); // } // // public static String convertBytesToHex(byte[] a) { // StringBuilder sb = new StringBuilder(a.length * 2); // for (byte b : a) // sb.append(String.format("%02x ", b & 0xff)); // return sb.toString(); // } // // public static String convertByteBufferToHex(final ByteBuffer buffer) { // final byte[] bytes = new byte[buffer.remaining()]; // buffer.duplicate().get(bytes); // return convertBytesToHex(bytes); // } // // public static short convertToShort(byte[] byteArray, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.put(byteArray, offset, 2); // b.rewind(); // return b.getShort(); // } // // /** // * Used to read the Vendor and Model descriptions. // */ // public static String bytesToString(byte[] answer, int offset, int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // buffer.put(answer, offset, length); // return new String(buffer.array()); // } // // public static void setBytesFromShort(short value, byte[] array, int offset, ByteOrder order) { // ByteBuffer b = ByteBuffer.allocate(2); // b.order(order); // b.putShort(value); // byte[] temp = b.array(); // // setBytes(temp, array, offset, 2); // } // // private static void setBytes(byte[] a, byte[] array, int offset, int length) { // for (int i = 0; i < length; i++) { // int index = offset + i; // array[index] = a[i]; // } // } // // public static byte[] forceCast(int[] input) { // byte[] output = new byte[input.length]; // for (int i = 0; i < output.length; i++) { // output[i] = (byte) input[i]; // } // return output; // } // } // Path: scsi/src/main/java/net/alphadev/usbstorage/partition/MasterBootRecord.java import net.alphadev.usbstorage.api.device.BlockDevice; import net.alphadev.usbstorage.util.BitStitching; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashSet; /** * Copyright © 2014-2015 Jan Seeger * * 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 net.alphadev.usbstorage.partition; /** * @author Jan Seeger <jan@alphadev.net> */ public class MasterBootRecord { private static final int SIGNATURE_OFFSET = 0x01FE; private static final int PARTITION_DATA_OFFSET = 0x1BE; private static final int PARTITION_DATA_LENGTH = 16; private final HashSet<Partition> mPartitions;
public MasterBootRecord(BlockDevice device) {
monitorjbl/json-view
spring-json-view/src/test/java/com/monitorjbl/json/server/Context.java
// Path: spring-json-view/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java // public class JsonViewSupportFactoryBean implements InitializingBean { // protected static final Logger log = LoggerFactory.getLogger(JsonViewSupportFactoryBean.class); // // @Autowired // protected RequestMappingHandlerAdapter adapter; // // protected final JsonViewMessageConverter converter; // protected final DefaultView defaultView; // // public JsonViewSupportFactoryBean() { // this(new ObjectMapper()); // } // // public JsonViewSupportFactoryBean(ObjectMapper mapper) { // this(new JsonViewMessageConverter(mapper.copy()), DefaultView.create()); // } // // public JsonViewSupportFactoryBean(DefaultView defaultView) { // this(new JsonViewMessageConverter(new ObjectMapper()), defaultView); // } // // public JsonViewSupportFactoryBean(ObjectMapper mapper, DefaultView defaultView) { // this(new JsonViewMessageConverter(mapper.copy()), defaultView); // } // // private JsonViewSupportFactoryBean(JsonViewMessageConverter converter, DefaultView defaultView) { // this.converter = converter; // this.defaultView = defaultView; // } // // @Override // public void afterPropertiesSet() throws Exception { // List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers()); // // List<HttpMessageConverter<?>> converters = removeJacksonConverters(adapter.getMessageConverters()); // converters.add(converter); // adapter.setMessageConverters(converters); // // decorateHandlers(handlers); // adapter.setReturnValueHandlers(handlers); // } // // protected List<HttpMessageConverter<?>> removeJacksonConverters(List<HttpMessageConverter<?>> converters) { // List<HttpMessageConverter<?>> copy = new ArrayList<>(converters); // Iterator<HttpMessageConverter<?>> iter = copy.iterator(); // while(iter.hasNext()) { // HttpMessageConverter<?> next = iter.next(); // if (next.getClass().getSimpleName().startsWith("MappingJackson2")) { // log.debug("Removing {} as it interferes with us", next.getClass().getName()); // iter.remove(); // } // } // return copy; // } // // protected void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) { // List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters()); // converters.add(converter); // for(HandlerMethodReturnValueHandler handler : handlers) { // int index = handlers.indexOf(handler); // if(handler instanceof HttpEntityMethodProcessor) { // handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters)); // } else if(handler instanceof RequestResponseBodyMethodProcessor) { // handlers.set(index, new JsonViewReturnValueHandler(converters, defaultView)); // break; // } // } // } // // // /** // * Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.<br> // * This way you could register for instance a JODA serialization as a DateTimeSerializer. <br> // * Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.<br> // * Example:<br> // * <code> // * JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); // * bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); // * </code> // * @param <T> Type class of the serializer // * @param cls {@link Class} the class type you want to add a custom serializer // * @param forType {@link JsonSerializer} the serializer you want to apply for that type // */ // public <T> void registerCustomSerializer( Class<T> cls, JsonSerializer<T> forType ) // { // this.converter.registerCustomSerializer( cls, forType ); // } // // // /** // * Unregister a previously registtered serializer. @see registerCustomSerializer // * @param cls The class type the serializer was registered for // */ // public void unregisterCustomSerializer( Class<?> cls ) // { // this.converter.unregisterCustomSerializer(cls); // } // // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.monitorjbl.json.JsonViewSupportFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
package com.monitorjbl.json.server; @EnableWebMvc @Configuration @ComponentScan({"com.monitorjbl.json.server"}) public class Context extends WebMvcConfigurerAdapter { @Bean
// Path: spring-json-view/src/main/java/com/monitorjbl/json/JsonViewSupportFactoryBean.java // public class JsonViewSupportFactoryBean implements InitializingBean { // protected static final Logger log = LoggerFactory.getLogger(JsonViewSupportFactoryBean.class); // // @Autowired // protected RequestMappingHandlerAdapter adapter; // // protected final JsonViewMessageConverter converter; // protected final DefaultView defaultView; // // public JsonViewSupportFactoryBean() { // this(new ObjectMapper()); // } // // public JsonViewSupportFactoryBean(ObjectMapper mapper) { // this(new JsonViewMessageConverter(mapper.copy()), DefaultView.create()); // } // // public JsonViewSupportFactoryBean(DefaultView defaultView) { // this(new JsonViewMessageConverter(new ObjectMapper()), defaultView); // } // // public JsonViewSupportFactoryBean(ObjectMapper mapper, DefaultView defaultView) { // this(new JsonViewMessageConverter(mapper.copy()), defaultView); // } // // private JsonViewSupportFactoryBean(JsonViewMessageConverter converter, DefaultView defaultView) { // this.converter = converter; // this.defaultView = defaultView; // } // // @Override // public void afterPropertiesSet() throws Exception { // List<HandlerMethodReturnValueHandler> handlers = new ArrayList<>(adapter.getReturnValueHandlers()); // // List<HttpMessageConverter<?>> converters = removeJacksonConverters(adapter.getMessageConverters()); // converters.add(converter); // adapter.setMessageConverters(converters); // // decorateHandlers(handlers); // adapter.setReturnValueHandlers(handlers); // } // // protected List<HttpMessageConverter<?>> removeJacksonConverters(List<HttpMessageConverter<?>> converters) { // List<HttpMessageConverter<?>> copy = new ArrayList<>(converters); // Iterator<HttpMessageConverter<?>> iter = copy.iterator(); // while(iter.hasNext()) { // HttpMessageConverter<?> next = iter.next(); // if (next.getClass().getSimpleName().startsWith("MappingJackson2")) { // log.debug("Removing {} as it interferes with us", next.getClass().getName()); // iter.remove(); // } // } // return copy; // } // // protected void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) { // List<HttpMessageConverter<?>> converters = new ArrayList<>(adapter.getMessageConverters()); // converters.add(converter); // for(HandlerMethodReturnValueHandler handler : handlers) { // int index = handlers.indexOf(handler); // if(handler instanceof HttpEntityMethodProcessor) { // handlers.set(index, new JsonViewHttpEntityMethodProcessor(converters)); // } else if(handler instanceof RequestResponseBodyMethodProcessor) { // handlers.set(index, new JsonViewReturnValueHandler(converters, defaultView)); // break; // } // } // } // // // /** // * Registering custom serializer allows to the JSonView to deal with custom serializations for certains field types.<br> // * This way you could register for instance a JODA serialization as a DateTimeSerializer. <br> // * Thus, when JSonView find a field of that type (DateTime), it will delegate the serialization to the serializer specified.<br> // * Example:<br> // * <code> // * JsonViewSupportFactoryBean bean = new JsonViewSupportFactoryBean( mapper ); // * bean.registerCustomSerializer( DateTime.class, new DateTimeSerializer() ); // * </code> // * @param <T> Type class of the serializer // * @param cls {@link Class} the class type you want to add a custom serializer // * @param forType {@link JsonSerializer} the serializer you want to apply for that type // */ // public <T> void registerCustomSerializer( Class<T> cls, JsonSerializer<T> forType ) // { // this.converter.registerCustomSerializer( cls, forType ); // } // // // /** // * Unregister a previously registtered serializer. @see registerCustomSerializer // * @param cls The class type the serializer was registered for // */ // public void unregisterCustomSerializer( Class<?> cls ) // { // this.converter.unregisterCustomSerializer(cls); // } // // } // Path: spring-json-view/src/test/java/com/monitorjbl/json/server/Context.java import com.fasterxml.jackson.databind.ObjectMapper; import com.monitorjbl.json.JsonViewSupportFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; package com.monitorjbl.json.server; @EnableWebMvc @Configuration @ComponentScan({"com.monitorjbl.json.server"}) public class Context extends WebMvcConfigurerAdapter { @Bean
public JsonViewSupportFactoryBean views() {
monitorjbl/json-view
spring-json-view/src/test/java/com/monitorjbl/json/JavaConfigurationTest.java
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/JavaConfigServer.java // public class JavaConfigServer implements ConfigServer{ // public static final Logger log = LoggerFactory.getLogger(JavaConfigServer.class); // private boolean running; // private Thread thread; // // public synchronized void start(final int port) { // if(thread != null) { // throw new IllegalStateException("Server is already running"); // } // // thread = new Thread(new Runnable() { // @Override // public void run() { // try { // Server server = new Server(port); // // final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); // applicationContext.register(Context.class); // // final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext)); // final ServletContextHandler context = new ServletContextHandler(); // context.setContextPath("/"); // context.addServlet(servletHolder, "/*"); // // server.setHandler(context); // // running = true; // server.start(); // log.info("Server started"); // // while(running) { // Thread.sleep(1); // } // // server.stop(); // log.info("Server stopped"); // } catch(Exception e) { // log.error("Server exception", e); // throw new RuntimeException(e); // } // } // }); // thread.start(); // } // // public void stop() { // running = false; // try { // thread.join(); // } catch(InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(String[] args) { // new JavaConfigServer().start(9090); // } // }
import com.monitorjbl.json.server.JavaConfigServer; import org.junit.BeforeClass;
package com.monitorjbl.json; public class JavaConfigurationTest extends ConfigTest { @BeforeClass() public static void init() throws Exception {
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/JavaConfigServer.java // public class JavaConfigServer implements ConfigServer{ // public static final Logger log = LoggerFactory.getLogger(JavaConfigServer.class); // private boolean running; // private Thread thread; // // public synchronized void start(final int port) { // if(thread != null) { // throw new IllegalStateException("Server is already running"); // } // // thread = new Thread(new Runnable() { // @Override // public void run() { // try { // Server server = new Server(port); // // final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); // applicationContext.register(Context.class); // // final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(applicationContext)); // final ServletContextHandler context = new ServletContextHandler(); // context.setContextPath("/"); // context.addServlet(servletHolder, "/*"); // // server.setHandler(context); // // running = true; // server.start(); // log.info("Server started"); // // while(running) { // Thread.sleep(1); // } // // server.stop(); // log.info("Server stopped"); // } catch(Exception e) { // log.error("Server exception", e); // throw new RuntimeException(e); // } // } // }); // thread.start(); // } // // public void stop() { // running = false; // try { // thread.join(); // } catch(InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(String[] args) { // new JavaConfigServer().start(9090); // } // } // Path: spring-json-view/src/test/java/com/monitorjbl/json/JavaConfigurationTest.java import com.monitorjbl.json.server.JavaConfigServer; import org.junit.BeforeClass; package com.monitorjbl.json; public class JavaConfigurationTest extends ConfigTest { @BeforeClass() public static void init() throws Exception {
server = new JavaConfigServer();
monitorjbl/json-view
json-view/src/main/java/com/monitorjbl/json/Memoizer.java
// Path: json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java // static class AccessibleProperty { // public final Class declaringClass; // public final String name; // public final Class type; // public final Annotation[] annotations; // public final int modifiers; // public final Object property; // private final Function<Object, Object> getter; // // public AccessibleProperty(String name, Annotation[] annotations, Object property) { // this.name = name; // this.annotations = annotations; // this.property = property; // // if(property instanceof Field) { // this.declaringClass = ((Field) property).getDeclaringClass(); // this.type = ((Field) property).getType(); // this.modifiers = ((Field) property).getModifiers(); // this.getter = this::getFromField; // } else if(property instanceof Method) { // this.declaringClass = ((Method) property).getDeclaringClass(); // this.type = ((Method) property).getReturnType(); // this.modifiers = ((Method) property).getModifiers(); // this.getter = this::getFromMethod; // } else { // throw new RuntimeException("Unable to access property from " + property); // } // } // // public Object get(Object obj) { // return getter.apply(obj); // } // // private Object getFromField(Object obj) { // try { // ((Field) property).setAccessible(true); // return ((Field) property).get(obj); // } catch(IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // private Object getFromMethod(Object obj) { // try { // ((Method) property).setAccessible(true); // return ((Method) property).invoke(obj); // } catch(IllegalAccessException | InvocationTargetException e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean equals(Object o) { // if(this == o) return true; // if(o == null || getClass() != o.getClass()) return false; // AccessibleProperty that = (AccessibleProperty) o; // return Objects.equals(declaringClass, that.declaringClass) && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // // return Objects.hash(declaringClass, name); // } // }
import com.monitorjbl.json.JsonViewSerializer.AccessibleProperty; import java.util.EnumMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import static com.monitorjbl.json.Memoizer.FunctionCache.ACCESSIBLE_PROPERTY; import static com.monitorjbl.json.Memoizer.FunctionCache.ANNOTATIONS; import static com.monitorjbl.json.Memoizer.FunctionCache.CLASS_MATCHES; import static com.monitorjbl.json.Memoizer.FunctionCache.IGNORE_ANNOTATIONS; import static com.monitorjbl.json.Memoizer.FunctionCache.MATCHES;
package com.monitorjbl.json; @SuppressWarnings("unchecked") class Memoizer { private final int maxCacheSize; private final Map<FunctionCache, Map<Arg, Object>> cache = new EnumMap<>(FunctionCache.class); public Memoizer(int maxCacheSize) { this.maxCacheSize = maxCacheSize; for(FunctionCache key : FunctionCache.class.getEnumConstants()) { cache.put(key, new ConcurrentHashMap<>()); } } public <T> T matches(Set<String> values, String pattern, boolean matchPrefix, Supplier<T> compute) { return computeIfAbsent(MATCHES, new TriArg(values, pattern, matchPrefix), compute); } public <T> T classMatches(JsonView jsonView, Class cls, Supplier<T> compute) { return computeIfAbsent(CLASS_MATCHES, new BiArg(jsonView, cls), compute); } public <T> T annotations(Class cls, Supplier<T> compute) { return computeIfAbsent(ANNOTATIONS, new MonoArg(cls), compute); }
// Path: json-view/src/main/java/com/monitorjbl/json/JsonViewSerializer.java // static class AccessibleProperty { // public final Class declaringClass; // public final String name; // public final Class type; // public final Annotation[] annotations; // public final int modifiers; // public final Object property; // private final Function<Object, Object> getter; // // public AccessibleProperty(String name, Annotation[] annotations, Object property) { // this.name = name; // this.annotations = annotations; // this.property = property; // // if(property instanceof Field) { // this.declaringClass = ((Field) property).getDeclaringClass(); // this.type = ((Field) property).getType(); // this.modifiers = ((Field) property).getModifiers(); // this.getter = this::getFromField; // } else if(property instanceof Method) { // this.declaringClass = ((Method) property).getDeclaringClass(); // this.type = ((Method) property).getReturnType(); // this.modifiers = ((Method) property).getModifiers(); // this.getter = this::getFromMethod; // } else { // throw new RuntimeException("Unable to access property from " + property); // } // } // // public Object get(Object obj) { // return getter.apply(obj); // } // // private Object getFromField(Object obj) { // try { // ((Field) property).setAccessible(true); // return ((Field) property).get(obj); // } catch(IllegalAccessException e) { // throw new RuntimeException(e); // } // } // // private Object getFromMethod(Object obj) { // try { // ((Method) property).setAccessible(true); // return ((Method) property).invoke(obj); // } catch(IllegalAccessException | InvocationTargetException e) { // throw new RuntimeException(e); // } // } // // @Override // public boolean equals(Object o) { // if(this == o) return true; // if(o == null || getClass() != o.getClass()) return false; // AccessibleProperty that = (AccessibleProperty) o; // return Objects.equals(declaringClass, that.declaringClass) && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // // return Objects.hash(declaringClass, name); // } // } // Path: json-view/src/main/java/com/monitorjbl/json/Memoizer.java import com.monitorjbl.json.JsonViewSerializer.AccessibleProperty; import java.util.EnumMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import static com.monitorjbl.json.Memoizer.FunctionCache.ACCESSIBLE_PROPERTY; import static com.monitorjbl.json.Memoizer.FunctionCache.ANNOTATIONS; import static com.monitorjbl.json.Memoizer.FunctionCache.CLASS_MATCHES; import static com.monitorjbl.json.Memoizer.FunctionCache.IGNORE_ANNOTATIONS; import static com.monitorjbl.json.Memoizer.FunctionCache.MATCHES; package com.monitorjbl.json; @SuppressWarnings("unchecked") class Memoizer { private final int maxCacheSize; private final Map<FunctionCache, Map<Arg, Object>> cache = new EnumMap<>(FunctionCache.class); public Memoizer(int maxCacheSize) { this.maxCacheSize = maxCacheSize; for(FunctionCache key : FunctionCache.class.getEnumConstants()) { cache.put(key, new ConcurrentHashMap<>()); } } public <T> T matches(Set<String> values, String pattern, boolean matchPrefix, Supplier<T> compute) { return computeIfAbsent(MATCHES, new TriArg(values, pattern, matchPrefix), compute); } public <T> T classMatches(JsonView jsonView, Class cls, Supplier<T> compute) { return computeIfAbsent(CLASS_MATCHES, new BiArg(jsonView, cls), compute); } public <T> T annotations(Class cls, Supplier<T> compute) { return computeIfAbsent(ANNOTATIONS, new MonoArg(cls), compute); }
public <T> T annotatedWithIgnore(AccessibleProperty property, Supplier<T> compute) {
monitorjbl/json-view
spring-json-view/src/test/java/com/monitorjbl/json/ConfigTest.java
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/ConfigServer.java // public interface ConfigServer { // public void start(int port); // // public void stop(); // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.monitorjbl.json.server.ConfigServer; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; import org.junit.AfterClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
package com.monitorjbl.json; public abstract class ConfigTest { protected static final Logger log = LoggerFactory.getLogger(XmlConfigurationTest.class);
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/ConfigServer.java // public interface ConfigServer { // public void start(int port); // // public void stop(); // } // Path: spring-json-view/src/test/java/com/monitorjbl/json/ConfigTest.java import com.fasterxml.jackson.databind.ObjectMapper; import com.monitorjbl.json.server.ConfigServer; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; import org.junit.AfterClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; package com.monitorjbl.json; public abstract class ConfigTest { protected static final Logger log = LoggerFactory.getLogger(XmlConfigurationTest.class);
protected static ConfigServer server;
monitorjbl/json-view
spring-json-view/src/test/java/com/monitorjbl/json/XmlConfigurationTest.java
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/XmlConfigServer.java // public class XmlConfigServer implements ConfigServer { // public static final Logger log = LoggerFactory.getLogger(XmlConfigServer.class); // private boolean running; // private Thread thread; // // public synchronized void start(final int port) { // if(thread != null) { // throw new IllegalStateException("Server is already running"); // } // // thread = new Thread(new Runnable() { // @Override // public void run() { // try { // Server server = new Server(port); // // final XmlWebApplicationContext xmlBasedContext = new XmlWebApplicationContext(); // //System.out.println(xmlBasedContext.getEnvironment().getClass()); // xmlBasedContext.setConfigLocation("classpath:context.xml"); // // final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(xmlBasedContext)); // final ServletContextHandler context = new ServletContextHandler(); // context.setContextPath("/"); // context.addServlet(servletHolder, "/*"); // server.setHandler(context); // // running = true; // server.start(); // log.info("Server started"); // // while(running) { // Thread.sleep(1); // } // // server.stop(); // log.info("Server stopped"); // } catch(Exception e) { // log.error("Server exception", e); // throw new RuntimeException(e); // } // } // }); // thread.start(); // } // // public void stop() { // running = false; // try { // thread.join(); // } catch(InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(String[] args) { // new XmlConfigServer().start(9090); // } // }
import com.monitorjbl.json.server.XmlConfigServer; import org.junit.BeforeClass;
package com.monitorjbl.json; public class XmlConfigurationTest extends ConfigTest { @BeforeClass() public static void init() throws Exception {
// Path: spring-json-view/src/test/java/com/monitorjbl/json/server/XmlConfigServer.java // public class XmlConfigServer implements ConfigServer { // public static final Logger log = LoggerFactory.getLogger(XmlConfigServer.class); // private boolean running; // private Thread thread; // // public synchronized void start(final int port) { // if(thread != null) { // throw new IllegalStateException("Server is already running"); // } // // thread = new Thread(new Runnable() { // @Override // public void run() { // try { // Server server = new Server(port); // // final XmlWebApplicationContext xmlBasedContext = new XmlWebApplicationContext(); // //System.out.println(xmlBasedContext.getEnvironment().getClass()); // xmlBasedContext.setConfigLocation("classpath:context.xml"); // // final ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(xmlBasedContext)); // final ServletContextHandler context = new ServletContextHandler(); // context.setContextPath("/"); // context.addServlet(servletHolder, "/*"); // server.setHandler(context); // // running = true; // server.start(); // log.info("Server started"); // // while(running) { // Thread.sleep(1); // } // // server.stop(); // log.info("Server stopped"); // } catch(Exception e) { // log.error("Server exception", e); // throw new RuntimeException(e); // } // } // }); // thread.start(); // } // // public void stop() { // running = false; // try { // thread.join(); // } catch(InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(String[] args) { // new XmlConfigServer().start(9090); // } // } // Path: spring-json-view/src/test/java/com/monitorjbl/json/XmlConfigurationTest.java import com.monitorjbl.json.server.XmlConfigServer; import org.junit.BeforeClass; package com.monitorjbl.json; public class XmlConfigurationTest extends ConfigTest { @BeforeClass() public static void init() throws Exception {
server = new XmlConfigServer();
rednaga/axmlprinter
src/test/java/android/content/res/chunk/sections/StringSectionTest.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package android.content.res.chunk.sections; /** * Created by diff on 9/29/15. */ public class StringSectionTest extends TestCase { private StringSection underTest;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // Path: src/test/java/android/content/res/chunk/sections/StringSectionTest.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package android.content.res.chunk.sections; /** * Created by diff on 9/29/15. */ public class StringSectionTest extends TestCase { private StringSection underTest;
private IntReader mockReader;
rednaga/axmlprinter
src/test/java/android/content/res/chunk/types/StartTagTest.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class StartTagTest extends TestCase { private StartTag underTest;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // Path: src/test/java/android/content/res/chunk/types/StartTagTest.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class StartTagTest extends TestCase { private StartTag underTest;
private IntReader mockReader;
rednaga/axmlprinter
src/main/java/android/content/res/chunk/types/GenericChunk.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * Abstract class for the generic lifting required by all Chunks * * @author tstrazzere */ public abstract class GenericChunk implements Chunk { private int startPosition; private ChunkType type; protected int size;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // Path: src/main/java/android/content/res/chunk/types/GenericChunk.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * Abstract class for the generic lifting required by all Chunks * * @author tstrazzere */ public abstract class GenericChunk implements Chunk { private int startPosition; private ChunkType type; protected int size;
public GenericChunk(ChunkType chunkType, IntReader reader) {
rednaga/axmlprinter
src/test/java/android/content/res/chunk/types/AttributeTest.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // }
import android.content.res.IntReader; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class AttributeTest extends TestCase { private Attribute underTest;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // Path: src/test/java/android/content/res/chunk/types/AttributeTest.java import android.content.res.IntReader; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class AttributeTest extends TestCase { private Attribute underTest;
private IntReader mockReader;
rednaga/axmlprinter
src/main/java/android/content/res/chunk/sections/ResourceSection.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // // Path: src/main/java/android/content/res/chunk/types/Chunk.java // public interface Chunk { // // /** // * Read the header section of the chunk // * // * @param reader // * @throws IOException // */ // public void readHeader(IntReader reader) throws IOException; // // /** // * @return the ChunkType for the current Chunk // */ // public ChunkType getChunkType(); // // /** // * @return the int size of the ChunkType // */ // public int getSize(); // // // XXX: Not sure this needs to exist // // /** // * @return a String representation of the Chunk // */ // public String toString(); // // /** // * @param stringSection // * @param resourceSection // * @param indent // * @return a String representation in XML form // */ // public String toXML(StringSection stringSection, ResourceSection resourceSection, int indent); // // /** // * Get the a byte[] for the chunk // * // * @return // */ // public byte[] toBytes(); // // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import android.content.res.chunk.types.Chunk; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.sections; /** * Concrete class for the section which is specifically for the resource ids. * * @author tstrazzere */ public class ResourceSection extends GenericChunkSection implements Chunk, ChunkSection { // TODO : Make this an ArrayList so it's easier to add/remove protected ArrayList<Integer> resourceIDs;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // // Path: src/main/java/android/content/res/chunk/types/Chunk.java // public interface Chunk { // // /** // * Read the header section of the chunk // * // * @param reader // * @throws IOException // */ // public void readHeader(IntReader reader) throws IOException; // // /** // * @return the ChunkType for the current Chunk // */ // public ChunkType getChunkType(); // // /** // * @return the int size of the ChunkType // */ // public int getSize(); // // // XXX: Not sure this needs to exist // // /** // * @return a String representation of the Chunk // */ // public String toString(); // // /** // * @param stringSection // * @param resourceSection // * @param indent // * @return a String representation in XML form // */ // public String toXML(StringSection stringSection, ResourceSection resourceSection, int indent); // // /** // * Get the a byte[] for the chunk // * // * @return // */ // public byte[] toBytes(); // // } // Path: src/main/java/android/content/res/chunk/sections/ResourceSection.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import android.content.res.chunk.types.Chunk; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.sections; /** * Concrete class for the section which is specifically for the resource ids. * * @author tstrazzere */ public class ResourceSection extends GenericChunkSection implements Chunk, ChunkSection { // TODO : Make this an ArrayList so it's easier to add/remove protected ArrayList<Integer> resourceIDs;
public ResourceSection(ChunkType chunkType, IntReader reader) {
rednaga/axmlprinter
src/test/java/android/content/res/chunk/types/TextTagTest.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class TextTagTest extends TestCase { private TextTag underTest;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // Path: src/test/java/android/content/res/chunk/types/TextTagTest.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import junit.framework.TestCase; import org.junit.Assert; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.types; /** * @author tstrazzere */ public class TextTagTest extends TestCase { private TextTag underTest;
private IntReader mockReader;
rednaga/axmlprinter
src/main/java/android/content/res/chunk/sections/StringSection.java
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // // Path: src/main/java/android/content/res/chunk/types/Chunk.java // public interface Chunk { // // /** // * Read the header section of the chunk // * // * @param reader // * @throws IOException // */ // public void readHeader(IntReader reader) throws IOException; // // /** // * @return the ChunkType for the current Chunk // */ // public ChunkType getChunkType(); // // /** // * @return the int size of the ChunkType // */ // public int getSize(); // // // XXX: Not sure this needs to exist // // /** // * @return a String representation of the Chunk // */ // public String toString(); // // /** // * @param stringSection // * @param resourceSection // * @param indent // * @return a String representation in XML form // */ // public String toXML(StringSection stringSection, ResourceSection resourceSection, int indent); // // /** // * Get the a byte[] for the chunk // * // * @return // */ // public byte[] toBytes(); // // }
import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import android.content.res.chunk.PoolItem; import android.content.res.chunk.types.Chunk; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays;
/* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.sections; public class StringSection extends GenericChunkSection implements Chunk, ChunkSection { // This specific tag appears unused but might need to be implemented? or used as an unknown? @SuppressWarnings("unused") private final int SORTED_FLAG = 1 << 0; private final int UTF8_FLAG = 1 << 8; private int stringChunkCount; private int styleChunkCount; private int stringChunkFlags; private int stringChunkPoolOffset; private int styleChunkPoolOffset; // FIXME: // This likely could just be an ordered array of Strings if the Integer is just ordered and the key.. private ArrayList<PoolItem> stringChunkPool; private ArrayList<PoolItem> styleChunkPool;
// Path: src/main/java/android/content/res/IntReader.java // public class IntReader { // // private InputStream stream; // private boolean bigEndian; // private int bytesRead; // // public IntReader(InputStream stream, boolean bigEndian) { // reset(stream, bigEndian); // } // // /** // * Reset the POJO to use a new stream. // * // * @param newStream the {@code InputStream} to use // * @param isBigEndian a boolean for whether or not the stream is in Big Endian format // */ // public void reset(InputStream newStream, boolean isBigEndian) { // stream = newStream; // bigEndian = isBigEndian; // bytesRead = 0; // } // // /** // * Close the current stream being used by the POJO. // */ // public void close() { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // reset(null, false); // } // } // // public int readByte() throws IOException { // return readInt(1); // } // // public int readShort() throws IOException { // return readInt(2); // } // // public int readInt() throws IOException { // return readInt(4); // } // // /** // * Read an integer of a certain length from the current stream. // * // * @param length to read // * @return // * @throws IOException // */ // public int readInt(int length) throws IOException { // if ((length < 0) || (length > 4)) { // throw new IllegalArgumentException(); // } // int result = 0; // int byteRead = 0; // if (bigEndian) { // for (int i = (length - 1) * 8; i >= 0; i -= 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } else { // length *= 8; // for (int i = 0; i != length; i += 8) { // byteRead = stream.read(); // bytesRead++; // if (byteRead == -1) { // throw new EOFException(); // } // result |= (byteRead << i); // } // } // // return result; // } // // /** // * Skip a specific number of bytes in the stream. // * // * @param bytes // * @throws IOException // */ // public void skip(int bytes) throws IOException { // if (bytes > 0) { // if (stream.skip(bytes) != bytes) { // throw new EOFException(); // } // bytesRead += bytes; // } // } // // public void skipInt() throws IOException { // skip(4); // } // // public int getBytesRead() { // return bytesRead; // } // } // // Path: src/main/java/android/content/res/chunk/types/Chunk.java // public interface Chunk { // // /** // * Read the header section of the chunk // * // * @param reader // * @throws IOException // */ // public void readHeader(IntReader reader) throws IOException; // // /** // * @return the ChunkType for the current Chunk // */ // public ChunkType getChunkType(); // // /** // * @return the int size of the ChunkType // */ // public int getSize(); // // // XXX: Not sure this needs to exist // // /** // * @return a String representation of the Chunk // */ // public String toString(); // // /** // * @param stringSection // * @param resourceSection // * @param indent // * @return a String representation in XML form // */ // public String toXML(StringSection stringSection, ResourceSection resourceSection, int indent); // // /** // * Get the a byte[] for the chunk // * // * @return // */ // public byte[] toBytes(); // // } // Path: src/main/java/android/content/res/chunk/sections/StringSection.java import android.content.res.IntReader; import android.content.res.chunk.ChunkType; import android.content.res.chunk.PoolItem; import android.content.res.chunk.types.Chunk; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; /* * Copyright 2015 Red Naga * * 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 android.content.res.chunk.sections; public class StringSection extends GenericChunkSection implements Chunk, ChunkSection { // This specific tag appears unused but might need to be implemented? or used as an unknown? @SuppressWarnings("unused") private final int SORTED_FLAG = 1 << 0; private final int UTF8_FLAG = 1 << 8; private int stringChunkCount; private int styleChunkCount; private int stringChunkFlags; private int stringChunkPoolOffset; private int styleChunkPoolOffset; // FIXME: // This likely could just be an ordered array of Strings if the Integer is just ordered and the key.. private ArrayList<PoolItem> stringChunkPool; private ArrayList<PoolItem> styleChunkPool;
public StringSection(ChunkType chunkType, IntReader inputReader) {