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
Djonique/Birdays
app/src/main/java/com/djonique/birdays/activities/HelpActivity.java
// Path: app/src/main/java/com/djonique/birdays/utils/Constants.java // public interface Constants { // // // Preferences // String CONTACTS_UPLOADED = "CONTACTS_UPLOADED"; // String WRONG_CONTACTS_FORMAT = "WRONG_CONTACTS_FORMAT"; // // // Permission requests // int READ_CONTACTS_PERMISSION_CODE = 1; // int WRITE_EXTERNAL_STORAGE_PERMISSION_CODE = 2; // int READ_EXTERNAL_STORAGE_PERMISSION_CODE = 3; // // // Alarm // String NAME = "NAME"; // String WHEN = "WHEN"; // String TIME_STAMP = "TIME_STAMP"; // // // Settings keys // String NOTIFICATIONS_KEY = "notifications_key"; // String NOTIFICATION_TIME_KEY = "notification_time_key"; // String ADDITIONAL_NOTIFICATION_KEY = "additional_notification_key"; // String RINGTONE_KEY = "ringtone_key"; // String NIGHT_MODE_KEY = "night_mode_key"; // String START_PAGE = "start_page_key"; // String DISPLAYED_AGE_KEY = "displayed_age_key"; // // // Intents // String TYPE_EMAIL = "message/rfc822"; // String MAILTO = "mailto:"; // String TYPE_SMS = "vnd.android-dir/mms-sms"; // String ADDRESS = "address"; // String SMSTO = "smsto:"; // String TEL = "tel: "; // }
import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.djonique.birdays.R; import com.djonique.birdays.utils.Constants; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
@Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } @OnClick(R.id.button_help_whitelist) void openBatteryOptimization() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { startActivity(Intent.createChooser(new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS), null)); } catch (ActivityNotFoundException e) { Toast.makeText(this, ACTIVITY_NOT_FOUND_EXCEPTION, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, R.string.help_whitelist_error, Toast.LENGTH_LONG).show(); } } @OnClick(R.id.button_help_settings) void openSettings() { startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); } @OnClick(R.id.button_help_email) void sendEmail() { String email = getString(R.string.birdays_email); Intent intent = new Intent(Intent.ACTION_SENDTO);
// Path: app/src/main/java/com/djonique/birdays/utils/Constants.java // public interface Constants { // // // Preferences // String CONTACTS_UPLOADED = "CONTACTS_UPLOADED"; // String WRONG_CONTACTS_FORMAT = "WRONG_CONTACTS_FORMAT"; // // // Permission requests // int READ_CONTACTS_PERMISSION_CODE = 1; // int WRITE_EXTERNAL_STORAGE_PERMISSION_CODE = 2; // int READ_EXTERNAL_STORAGE_PERMISSION_CODE = 3; // // // Alarm // String NAME = "NAME"; // String WHEN = "WHEN"; // String TIME_STAMP = "TIME_STAMP"; // // // Settings keys // String NOTIFICATIONS_KEY = "notifications_key"; // String NOTIFICATION_TIME_KEY = "notification_time_key"; // String ADDITIONAL_NOTIFICATION_KEY = "additional_notification_key"; // String RINGTONE_KEY = "ringtone_key"; // String NIGHT_MODE_KEY = "night_mode_key"; // String START_PAGE = "start_page_key"; // String DISPLAYED_AGE_KEY = "displayed_age_key"; // // // Intents // String TYPE_EMAIL = "message/rfc822"; // String MAILTO = "mailto:"; // String TYPE_SMS = "vnd.android-dir/mms-sms"; // String ADDRESS = "address"; // String SMSTO = "smsto:"; // String TEL = "tel: "; // } // Path: app/src/main/java/com/djonique/birdays/activities/HelpActivity.java import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.djonique.birdays.R; import com.djonique.birdays.utils.Constants; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } @OnClick(R.id.button_help_whitelist) void openBatteryOptimization() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { startActivity(Intent.createChooser(new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS), null)); } catch (ActivityNotFoundException e) { Toast.makeText(this, ACTIVITY_NOT_FOUND_EXCEPTION, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, R.string.help_whitelist_error, Toast.LENGTH_LONG).show(); } } @OnClick(R.id.button_help_settings) void openSettings() { startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); } @OnClick(R.id.button_help_email) void sendEmail() { String email = getString(R.string.birdays_email); Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType(Constants.TYPE_EMAIL);
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/client/audio/Sound.java
// Path: src/main/java/org/newdawn/slick/openal/OggDecoder.java // public class OggDecoder { // /** The conversion buffer size */ // private int convsize = 4096 * 4; // /** The buffer used to read OGG file */ // private byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack // // /** // * Create a new OGG decoder // */ // public OggDecoder() { // } // // /** // * Get the data out of an OGG file // * // * @param input The input stream from which to read the OGG file // * @return The data describing the OGG thats been read // * @throws IOException Indicaites a failure to read the OGG file // */ // public OggData getData(InputStream input) throws IOException { // if (input == null) { // throw new IOException("Failed to read OGG, source does not exist?"); // } // ByteArrayOutputStream dataout = new ByteArrayOutputStream(); // // OggInputStream oggInput = new OggInputStream(input); // // boolean done = false; // while (!oggInput.atEnd()) { // dataout.write(oggInput.read()); // } // // OggData ogg = new OggData(); // ogg.channels = oggInput.getChannels(); // ogg.rate = oggInput.getRate(); // // byte[] data = dataout.toByteArray(); // ogg.data = ByteBuffer.allocateDirect(data.length); // ogg.data.put(data); // ogg.data.rewind(); // // return ogg; // } // }
import org.newdawn.slick.openal.OggData; import org.newdawn.slick.openal.OggDecoder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import static org.lwjgl.openal.AL10.*;
package org.flamierawieo.x00FA9A.client.audio; public class Sound { private Integer source; private int buffer; public static Sound loadFromOggFile(File file) throws IOException {
// Path: src/main/java/org/newdawn/slick/openal/OggDecoder.java // public class OggDecoder { // /** The conversion buffer size */ // private int convsize = 4096 * 4; // /** The buffer used to read OGG file */ // private byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack // // /** // * Create a new OGG decoder // */ // public OggDecoder() { // } // // /** // * Get the data out of an OGG file // * // * @param input The input stream from which to read the OGG file // * @return The data describing the OGG thats been read // * @throws IOException Indicaites a failure to read the OGG file // */ // public OggData getData(InputStream input) throws IOException { // if (input == null) { // throw new IOException("Failed to read OGG, source does not exist?"); // } // ByteArrayOutputStream dataout = new ByteArrayOutputStream(); // // OggInputStream oggInput = new OggInputStream(input); // // boolean done = false; // while (!oggInput.atEnd()) { // dataout.write(oggInput.read()); // } // // OggData ogg = new OggData(); // ogg.channels = oggInput.getChannels(); // ogg.rate = oggInput.getRate(); // // byte[] data = dataout.toByteArray(); // ogg.data = ByteBuffer.allocateDirect(data.length); // ogg.data.put(data); // ogg.data.rewind(); // // return ogg; // } // } // Path: src/main/java/org/flamierawieo/x00FA9A/client/audio/Sound.java import org.newdawn.slick.openal.OggData; import org.newdawn.slick.openal.OggDecoder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import static org.lwjgl.openal.AL10.*; package org.flamierawieo.x00FA9A.client.audio; public class Sound { private Integer source; private int buffer; public static Sound loadFromOggFile(File file) throws IOException {
OggData oggData = new OggDecoder().getData(new FileInputStream(file));
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/client/graphics/Text.java
// Path: src/main/java/org/flamierawieo/x00FA9A/client/settings/Settings.java // public class Settings { // // private static Settings instance = new Settings(); // // public static Settings getInstance() { // return instance; // } // // public static final String userSettingsJsonPath = "custom/user_settings.json"; // // private VideoMode videoMode; // // private Settings() { // JSONParser jsonParser = new JSONParser(); // try { // JSONObject userSettingsJson = (JSONObject) jsonParser.parse(new FileReader(userSettingsJsonPath)); // videoMode = VideoMode.getVideoModeById((String) userSettingsJson.get("video_mode")); // } catch (IOException | ParseException e) { // // file does not exists or is invalid // // generatin' new one, m8 // save(); // } // } // // public VideoMode getVideoMode() { // return videoMode; // } // // public void setVideoMode(VideoMode videoMode) { // this.videoMode = videoMode; // } // // public void save() { // try { // FileWriter fileWriter = new FileWriter(userSettingsJsonPath); // fileWriter.write(getJson().toJSONString()); // fileWriter.flush(); // fileWriter.close(); // } catch(IOException e) { // e.printStackTrace(); // } // } // // public JSONObject getJson() { // JSONObject jsonObject = new JSONObject(); // if(videoMode != null) { // jsonObject.put("video_mode", videoMode.getId()); // } // return jsonObject; // } // // }
import org.flamierawieo.x00FA9A.client.settings.Settings; import org.lwjgl.BufferUtils; import java.awt.*; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import static org.lwjgl.opengl.GL11.*;
public Font getFont() { return font; } public void setFont(Font font) { this.font = font; updateTexture(); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; updateTexture(); } public float getWidth() { return width; } public float getHeight() { return height; } private void updateTexture() { BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = bufferedImage.createGraphics();
// Path: src/main/java/org/flamierawieo/x00FA9A/client/settings/Settings.java // public class Settings { // // private static Settings instance = new Settings(); // // public static Settings getInstance() { // return instance; // } // // public static final String userSettingsJsonPath = "custom/user_settings.json"; // // private VideoMode videoMode; // // private Settings() { // JSONParser jsonParser = new JSONParser(); // try { // JSONObject userSettingsJson = (JSONObject) jsonParser.parse(new FileReader(userSettingsJsonPath)); // videoMode = VideoMode.getVideoModeById((String) userSettingsJson.get("video_mode")); // } catch (IOException | ParseException e) { // // file does not exists or is invalid // // generatin' new one, m8 // save(); // } // } // // public VideoMode getVideoMode() { // return videoMode; // } // // public void setVideoMode(VideoMode videoMode) { // this.videoMode = videoMode; // } // // public void save() { // try { // FileWriter fileWriter = new FileWriter(userSettingsJsonPath); // fileWriter.write(getJson().toJSONString()); // fileWriter.flush(); // fileWriter.close(); // } catch(IOException e) { // e.printStackTrace(); // } // } // // public JSONObject getJson() { // JSONObject jsonObject = new JSONObject(); // if(videoMode != null) { // jsonObject.put("video_mode", videoMode.getId()); // } // return jsonObject; // } // // } // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Text.java import org.flamierawieo.x00FA9A.client.settings.Settings; import org.lwjgl.BufferUtils; import java.awt.*; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import static org.lwjgl.opengl.GL11.*; public Font getFont() { return font; } public void setFont(Font font) { this.font = font; updateTexture(); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; updateTexture(); } public float getWidth() { return width; } public float getHeight() { return height; } private void updateTexture() { BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = bufferedImage.createGraphics();
Font scaledFont = font.deriveFont(Settings.getInstance().getVideoMode().getHeight() * this.height); // TODO: redesign project's WHOLE FUCKING ARCHITECTURE
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/client/ui/Cursor.java
// Path: src/main/java/org/flamierawieo/x00FA9A/client/Images.java // public enum Images { // // CURSOR_IMAGE ("res/images/cursor.png"), // BASIC_BACKGROUND ("res/images/background.png"), // TEST ("custom/beatmaps/6fb2cf0d Truxton - Alexandrian Ricochet Sphere/background.png"), // // // Start menu and player widget // MENU_BUTTON ("res/images/startmenu/menu-buttons.png"), // PLAY ("res/images/playerwidget/play.png"), // PAUSE ("res/images/playerwidget/pause.png"), // // //Settings menu // SETTINGS_BACKGROUND ("res/images/settingsmenu/settings-background.png"), // SETTINGS_LINE ("res/images/settingsmenu/settings-line.png"), // // // Song menu // SONG_LIST_BACKGROUND ("res/images/songmenu/song-list-background.png"), // ACTIVE_SONG_BACKGROUND ("res/images/songmenu/active-song-background.png"), // SEARCH_BACKGROUND ("res/images/songmenu/search-background.png"), // SELECT_MODE ("res/images/songmenu/logo-background.png"), // BOTTOM_PANEL ("res/images/songmenu/bottom-panel-background.png"), // MAP_HEADER ("res/images/songmenu/map-header-background.png"), // // circles // SELECTED_DIFFICULTY ("res/images/songmenu/selected-difficulty-mark.png"), // AVAILABLE_DIFFICULTY ("res/images/songmenu/available-difficulty-mark.png"), // UNAVAILABLE_DIFFICULTY ("res/images/songmenu/unavailable-difficulty-mark.png"), // // // Square mode backgrounds // BUTTONS_BACKGROUND ("res/images/squaremode/buttons-background.png"), // COMBO_BACKGROUND ("res/images/squaremode/combo-background.png"), // HP_BACKGROUND ("res/images/squaremode/hp-background.png"), // STATS_BACKGROUND ("res/images/squaremode/stats-background.png"), // // // Square mode buttons // GREEN_BUTTON ("res/images/squaremode/green-button.png"), // PINK_BUTTON ("res/images/squaremode/pink-button.png"); // // private String path; // private Integer texture; // // /** // * Basic image // * @param path to the image // */ // Images(String path) { // this.path = path; // texture = null; // } // // /** // * @return OpenGL texture // */ // public int getTexture() { // if(texture == null) { // texture = Resources.getTexture(path); // } // return texture; // } // // public static void whatDoesNicktaelSaid() { // Logger.getLogger("Nickta").log(Level.WARNING, "THIS DANK CODE IS 2COOL4U"); // MAJESTIC GLORIOUS // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Drawable.java // public interface Drawable { // // void draw(); // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Sprite.java // public class Sprite { // // private Integer texture; // // public Sprite(Integer texture) { // this.texture = texture; // } // // public Integer getTexture() { // return texture; // } // // public void setTexture(int texture) { // this.texture = texture; // } // // public void draw(float x, float y, float width, float height) { // if(texture != null) { // glPushMatrix(); // glTranslatef(x, y, 0.0f); // glColor3f(1.0f, 1.0f, 1.0f); // glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, texture); // glBegin(GL_QUADS); // glTexCoord2f(0.0f, 0.0f); // glVertex3f(0.0f, height, 0.0f); // glTexCoord2f(1.0f, 0.0f); // glVertex3f(width, height, 0.0f); // glTexCoord2f(1.0f, 1.0f); // glVertex3f(width, 0.0f, 0.0f); // glTexCoord2f(0.0f, 1.0f); // glVertex3f(0.0f, 0.0f, 0.0f); // glEnd(); // glDisable(GL_TEXTURE_2D); // glPopMatrix(); // } // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/input/MouseInputListener.java // public interface MouseInputListener { // // void onMouseMove(float x, float y); // void onMouseButtonDown(float x, float y, int button, int mods); // void onMouseButtonUp(float x, float y, int button, int mods); // void onScroll(float x, float y, double scrollX, double scrollY); // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/shared/Tickable.java // public interface Tickable { // // void tick(float delta); // // }
import org.flamierawieo.x00FA9A.client.Images; import org.flamierawieo.x00FA9A.client.graphics.Drawable; import org.flamierawieo.x00FA9A.client.graphics.Sprite; import org.flamierawieo.x00FA9A.client.input.MouseInputListener; import org.flamierawieo.x00FA9A.shared.Tickable;
package org.flamierawieo.x00FA9A.client.ui; public class Cursor implements Tickable, Drawable, MouseInputListener { private Sprite sprite; private float x; private float y; public Cursor() {
// Path: src/main/java/org/flamierawieo/x00FA9A/client/Images.java // public enum Images { // // CURSOR_IMAGE ("res/images/cursor.png"), // BASIC_BACKGROUND ("res/images/background.png"), // TEST ("custom/beatmaps/6fb2cf0d Truxton - Alexandrian Ricochet Sphere/background.png"), // // // Start menu and player widget // MENU_BUTTON ("res/images/startmenu/menu-buttons.png"), // PLAY ("res/images/playerwidget/play.png"), // PAUSE ("res/images/playerwidget/pause.png"), // // //Settings menu // SETTINGS_BACKGROUND ("res/images/settingsmenu/settings-background.png"), // SETTINGS_LINE ("res/images/settingsmenu/settings-line.png"), // // // Song menu // SONG_LIST_BACKGROUND ("res/images/songmenu/song-list-background.png"), // ACTIVE_SONG_BACKGROUND ("res/images/songmenu/active-song-background.png"), // SEARCH_BACKGROUND ("res/images/songmenu/search-background.png"), // SELECT_MODE ("res/images/songmenu/logo-background.png"), // BOTTOM_PANEL ("res/images/songmenu/bottom-panel-background.png"), // MAP_HEADER ("res/images/songmenu/map-header-background.png"), // // circles // SELECTED_DIFFICULTY ("res/images/songmenu/selected-difficulty-mark.png"), // AVAILABLE_DIFFICULTY ("res/images/songmenu/available-difficulty-mark.png"), // UNAVAILABLE_DIFFICULTY ("res/images/songmenu/unavailable-difficulty-mark.png"), // // // Square mode backgrounds // BUTTONS_BACKGROUND ("res/images/squaremode/buttons-background.png"), // COMBO_BACKGROUND ("res/images/squaremode/combo-background.png"), // HP_BACKGROUND ("res/images/squaremode/hp-background.png"), // STATS_BACKGROUND ("res/images/squaremode/stats-background.png"), // // // Square mode buttons // GREEN_BUTTON ("res/images/squaremode/green-button.png"), // PINK_BUTTON ("res/images/squaremode/pink-button.png"); // // private String path; // private Integer texture; // // /** // * Basic image // * @param path to the image // */ // Images(String path) { // this.path = path; // texture = null; // } // // /** // * @return OpenGL texture // */ // public int getTexture() { // if(texture == null) { // texture = Resources.getTexture(path); // } // return texture; // } // // public static void whatDoesNicktaelSaid() { // Logger.getLogger("Nickta").log(Level.WARNING, "THIS DANK CODE IS 2COOL4U"); // MAJESTIC GLORIOUS // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Drawable.java // public interface Drawable { // // void draw(); // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Sprite.java // public class Sprite { // // private Integer texture; // // public Sprite(Integer texture) { // this.texture = texture; // } // // public Integer getTexture() { // return texture; // } // // public void setTexture(int texture) { // this.texture = texture; // } // // public void draw(float x, float y, float width, float height) { // if(texture != null) { // glPushMatrix(); // glTranslatef(x, y, 0.0f); // glColor3f(1.0f, 1.0f, 1.0f); // glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, texture); // glBegin(GL_QUADS); // glTexCoord2f(0.0f, 0.0f); // glVertex3f(0.0f, height, 0.0f); // glTexCoord2f(1.0f, 0.0f); // glVertex3f(width, height, 0.0f); // glTexCoord2f(1.0f, 1.0f); // glVertex3f(width, 0.0f, 0.0f); // glTexCoord2f(0.0f, 1.0f); // glVertex3f(0.0f, 0.0f, 0.0f); // glEnd(); // glDisable(GL_TEXTURE_2D); // glPopMatrix(); // } // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/input/MouseInputListener.java // public interface MouseInputListener { // // void onMouseMove(float x, float y); // void onMouseButtonDown(float x, float y, int button, int mods); // void onMouseButtonUp(float x, float y, int button, int mods); // void onScroll(float x, float y, double scrollX, double scrollY); // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/shared/Tickable.java // public interface Tickable { // // void tick(float delta); // // } // Path: src/main/java/org/flamierawieo/x00FA9A/client/ui/Cursor.java import org.flamierawieo.x00FA9A.client.Images; import org.flamierawieo.x00FA9A.client.graphics.Drawable; import org.flamierawieo.x00FA9A.client.graphics.Sprite; import org.flamierawieo.x00FA9A.client.input.MouseInputListener; import org.flamierawieo.x00FA9A.shared.Tickable; package org.flamierawieo.x00FA9A.client.ui; public class Cursor implements Tickable, Drawable, MouseInputListener { private Sprite sprite; private float x; private float y; public Cursor() {
sprite = new Sprite(Images.CURSOR_IMAGE.getTexture());
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/x00FA9A.java
// Path: src/main/java/org/flamierawieo/x00FA9A/client/x00FA9AClient.java // public class x00FA9AClient { // // private static long window; // private static ALContext context; // // public static void init() { // if(glfwInit() != GL_TRUE) { // throw new IllegalStateException("Unable to initialize GLFW"); // } // glfwDefaultWindowHints(); // glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // long primaryMonitor = glfwGetPrimaryMonitor(); // Settings settings = Settings.getInstance(); // VideoMode videoMode = settings.getVideoMode(); // int initialWindowWidth; // int initialWindowHeight; // if(videoMode == null) { // int scale = "true".equals(System.getProperty("retina")) ? 2 : 1; // GLFWVidMode vidMode = glfwGetVideoMode(primaryMonitor); // videoMode = VideoMode.getAutoDetectedVideoMode(vidMode.width() * scale, vidMode.height() * scale); // settings.setVideoMode(videoMode); // settings.save(); // initialWindowWidth = videoMode.getWidth(); // initialWindowHeight = videoMode.getHeight(); // } else { // initialWindowWidth = videoMode.getWidth(); // initialWindowHeight = videoMode.getHeight(); // } // window = glfwCreateWindow(initialWindowWidth, initialWindowHeight, "Beat Party", primaryMonitor, NULL); // glfwMakeContextCurrent(window); // glfwSwapInterval(0); // glfwShowWindow(window); // GL.createCapabilities(false); // context = ALContext.create(); // if(!context.getCapabilities().OpenAL10) { // throw new IllegalStateException("Failed to create OpenAL context"); // } // context.makeCurrent(); // alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); // alListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f); // ViewManager.init(initialWindowWidth, initialWindowHeight, new SongMenu()); // glfwSetKeyCallback(window, ViewManager.getGlfwKeyCallback()); // glfwSetCursorPosCallback(window, ViewManager.getGlfwCursorPosCallback()); // glfwSetMouseButtonCallback(window, ViewManager.getGlfwMouseButtonCallback()); // glfwSetScrollCallback(window, ViewManager.getGlfwScrollCallback()); // } // // public static void run() { // glEnable(GL_BLEND); // glEnable(GL_POLYGON_SMOOTH); // glEnable(GL_LINE_SMOOTH); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glClearColor(0.0f, 0.98f, 0.60f, 0.0f); // // // int vertexShader = Resources.getShader("res/shaders/shadow_vertex_shader.glsl", GL_VERTEX_SHADER); // // int fragmentShader = Resources.getShader("res/shaders/shadow_fragment_shader.glsl", GL_FRAGMENT_SHADER); // // int program = glCreateProgram(); // // glAttachShader(program, vertexShader); // // glAttachShader(program, fragmentShader); // // glLinkProgram(program); // // glValidateProgram(program); // // int status = glGetProgrami(program, GL_LINK_STATUS); // // System.out.println(status == GL_TRUE); // // glUseProgram(program); // // float lastUpdateTime = (float)glfwGetTime(); // while(glfwWindowShouldClose(window) == GL_FALSE) { // tick((float)glfwGetTime() - lastUpdateTime); // draw(); // lastUpdateTime = (float)glfwGetTime(); // } // glDisable(GL_LINE_SMOOTH); // glDisable(GL_POLYGON_SMOOTH); // glDisable(GL_BLEND); // glfwDestroyWindow(window); // glfwTerminate(); // context.destroy(); // ALC.destroy(); // } // // public static void tick(float delta) { // glfwPollEvents(); // ViewManager.tick(delta); // } // // public static void draw() { // glClear(GL_COLOR_BUFFER_BIT); // ViewManager.draw(); // glfwSwapBuffers(window); // } // // }
import org.flamierawieo.x00FA9A.client.x00FA9AClient;
package org.flamierawieo.x00FA9A; public class x00FA9A { public static void main(String[] args) {
// Path: src/main/java/org/flamierawieo/x00FA9A/client/x00FA9AClient.java // public class x00FA9AClient { // // private static long window; // private static ALContext context; // // public static void init() { // if(glfwInit() != GL_TRUE) { // throw new IllegalStateException("Unable to initialize GLFW"); // } // glfwDefaultWindowHints(); // glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // long primaryMonitor = glfwGetPrimaryMonitor(); // Settings settings = Settings.getInstance(); // VideoMode videoMode = settings.getVideoMode(); // int initialWindowWidth; // int initialWindowHeight; // if(videoMode == null) { // int scale = "true".equals(System.getProperty("retina")) ? 2 : 1; // GLFWVidMode vidMode = glfwGetVideoMode(primaryMonitor); // videoMode = VideoMode.getAutoDetectedVideoMode(vidMode.width() * scale, vidMode.height() * scale); // settings.setVideoMode(videoMode); // settings.save(); // initialWindowWidth = videoMode.getWidth(); // initialWindowHeight = videoMode.getHeight(); // } else { // initialWindowWidth = videoMode.getWidth(); // initialWindowHeight = videoMode.getHeight(); // } // window = glfwCreateWindow(initialWindowWidth, initialWindowHeight, "Beat Party", primaryMonitor, NULL); // glfwMakeContextCurrent(window); // glfwSwapInterval(0); // glfwShowWindow(window); // GL.createCapabilities(false); // context = ALContext.create(); // if(!context.getCapabilities().OpenAL10) { // throw new IllegalStateException("Failed to create OpenAL context"); // } // context.makeCurrent(); // alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); // alListener3f(AL_VELOCITY, 0.0f, 0.0f, 0.0f); // ViewManager.init(initialWindowWidth, initialWindowHeight, new SongMenu()); // glfwSetKeyCallback(window, ViewManager.getGlfwKeyCallback()); // glfwSetCursorPosCallback(window, ViewManager.getGlfwCursorPosCallback()); // glfwSetMouseButtonCallback(window, ViewManager.getGlfwMouseButtonCallback()); // glfwSetScrollCallback(window, ViewManager.getGlfwScrollCallback()); // } // // public static void run() { // glEnable(GL_BLEND); // glEnable(GL_POLYGON_SMOOTH); // glEnable(GL_LINE_SMOOTH); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glClearColor(0.0f, 0.98f, 0.60f, 0.0f); // // // int vertexShader = Resources.getShader("res/shaders/shadow_vertex_shader.glsl", GL_VERTEX_SHADER); // // int fragmentShader = Resources.getShader("res/shaders/shadow_fragment_shader.glsl", GL_FRAGMENT_SHADER); // // int program = glCreateProgram(); // // glAttachShader(program, vertexShader); // // glAttachShader(program, fragmentShader); // // glLinkProgram(program); // // glValidateProgram(program); // // int status = glGetProgrami(program, GL_LINK_STATUS); // // System.out.println(status == GL_TRUE); // // glUseProgram(program); // // float lastUpdateTime = (float)glfwGetTime(); // while(glfwWindowShouldClose(window) == GL_FALSE) { // tick((float)glfwGetTime() - lastUpdateTime); // draw(); // lastUpdateTime = (float)glfwGetTime(); // } // glDisable(GL_LINE_SMOOTH); // glDisable(GL_POLYGON_SMOOTH); // glDisable(GL_BLEND); // glfwDestroyWindow(window); // glfwTerminate(); // context.destroy(); // ALC.destroy(); // } // // public static void tick(float delta) { // glfwPollEvents(); // ViewManager.tick(delta); // } // // public static void draw() { // glClear(GL_COLOR_BUFFER_BIT); // ViewManager.draw(); // glfwSwapBuffers(window); // } // // } // Path: src/main/java/org/flamierawieo/x00FA9A/x00FA9A.java import org.flamierawieo.x00FA9A.client.x00FA9AClient; package org.flamierawieo.x00FA9A; public class x00FA9A { public static void main(String[] args) {
x00FA9AClient.init();
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/client/Resources.java
// Path: src/main/java/org/newdawn/slick/openal/OggDecoder.java // public class OggDecoder { // /** The conversion buffer size */ // private int convsize = 4096 * 4; // /** The buffer used to read OGG file */ // private byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack // // /** // * Create a new OGG decoder // */ // public OggDecoder() { // } // // /** // * Get the data out of an OGG file // * // * @param input The input stream from which to read the OGG file // * @return The data describing the OGG thats been read // * @throws IOException Indicaites a failure to read the OGG file // */ // public OggData getData(InputStream input) throws IOException { // if (input == null) { // throw new IOException("Failed to read OGG, source does not exist?"); // } // ByteArrayOutputStream dataout = new ByteArrayOutputStream(); // // OggInputStream oggInput = new OggInputStream(input); // // boolean done = false; // while (!oggInput.atEnd()) { // dataout.write(oggInput.read()); // } // // OggData ogg = new OggData(); // ogg.channels = oggInput.getChannels(); // ogg.rate = oggInput.getRate(); // // byte[] data = dataout.toByteArray(); // ogg.data = ByteBuffer.allocateDirect(data.length); // ogg.data.put(data); // ogg.data.rewind(); // // return ogg; // } // }
import de.matthiasmann.twl.utils.PNGDecoder; import org.newdawn.slick.openal.OggData; import org.newdawn.slick.openal.OggDecoder; import java.io.*; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import static org.lwjgl.openal.AL10.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL20.*;
package org.flamierawieo.x00FA9A.client; public class Resources { private static Map<String, Integer> textures = new HashMap<>(); private static Integer missingTextureTextureID; private static Map<String, Integer> sounds = new HashMap<>(); private static Map<String, Integer> shaders = new HashMap<>(); private static int loadTextureFromPNG(String path) throws IOException { InputStream inputStream = new FileInputStream(path); PNGDecoder decoder = new PNGDecoder(inputStream); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(byteBuffer, decoder.getWidth() * 4, PNGDecoder.Format.RGBA); byteBuffer.flip(); inputStream.close(); int textureID = glGenTextures(); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); glDisable(GL_TEXTURE_2D); return textureID; } private static int loadSoundFromOgg(String path) throws IOException {
// Path: src/main/java/org/newdawn/slick/openal/OggDecoder.java // public class OggDecoder { // /** The conversion buffer size */ // private int convsize = 4096 * 4; // /** The buffer used to read OGG file */ // private byte[] convbuffer = new byte[convsize]; // take 8k out of the data segment, not the stack // // /** // * Create a new OGG decoder // */ // public OggDecoder() { // } // // /** // * Get the data out of an OGG file // * // * @param input The input stream from which to read the OGG file // * @return The data describing the OGG thats been read // * @throws IOException Indicaites a failure to read the OGG file // */ // public OggData getData(InputStream input) throws IOException { // if (input == null) { // throw new IOException("Failed to read OGG, source does not exist?"); // } // ByteArrayOutputStream dataout = new ByteArrayOutputStream(); // // OggInputStream oggInput = new OggInputStream(input); // // boolean done = false; // while (!oggInput.atEnd()) { // dataout.write(oggInput.read()); // } // // OggData ogg = new OggData(); // ogg.channels = oggInput.getChannels(); // ogg.rate = oggInput.getRate(); // // byte[] data = dataout.toByteArray(); // ogg.data = ByteBuffer.allocateDirect(data.length); // ogg.data.put(data); // ogg.data.rewind(); // // return ogg; // } // } // Path: src/main/java/org/flamierawieo/x00FA9A/client/Resources.java import de.matthiasmann.twl.utils.PNGDecoder; import org.newdawn.slick.openal.OggData; import org.newdawn.slick.openal.OggDecoder; import java.io.*; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import static org.lwjgl.openal.AL10.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL20.*; package org.flamierawieo.x00FA9A.client; public class Resources { private static Map<String, Integer> textures = new HashMap<>(); private static Integer missingTextureTextureID; private static Map<String, Integer> sounds = new HashMap<>(); private static Map<String, Integer> shaders = new HashMap<>(); private static int loadTextureFromPNG(String path) throws IOException { InputStream inputStream = new FileInputStream(path); PNGDecoder decoder = new PNGDecoder(inputStream); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * decoder.getWidth() * decoder.getHeight()); decoder.decode(byteBuffer, decoder.getWidth() * 4, PNGDecoder.Format.RGBA); byteBuffer.flip(); inputStream.close(); int textureID = glGenTextures(); glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer); glDisable(GL_TEXTURE_2D); return textureID; } private static int loadSoundFromOgg(String path) throws IOException {
OggData oggData = new OggDecoder().getData(new FileInputStream(path));
Ctyode/x00FA9A
src/main/java/org/flamierawieo/x00FA9A/client/ui/ViewManager.java
// Path: src/main/java/org/flamierawieo/x00FA9A/client/Images.java // public enum Images { // // CURSOR_IMAGE ("res/images/cursor.png"), // BASIC_BACKGROUND ("res/images/background.png"), // TEST ("custom/beatmaps/6fb2cf0d Truxton - Alexandrian Ricochet Sphere/background.png"), // // // Start menu and player widget // MENU_BUTTON ("res/images/startmenu/menu-buttons.png"), // PLAY ("res/images/playerwidget/play.png"), // PAUSE ("res/images/playerwidget/pause.png"), // // //Settings menu // SETTINGS_BACKGROUND ("res/images/settingsmenu/settings-background.png"), // SETTINGS_LINE ("res/images/settingsmenu/settings-line.png"), // // // Song menu // SONG_LIST_BACKGROUND ("res/images/songmenu/song-list-background.png"), // ACTIVE_SONG_BACKGROUND ("res/images/songmenu/active-song-background.png"), // SEARCH_BACKGROUND ("res/images/songmenu/search-background.png"), // SELECT_MODE ("res/images/songmenu/logo-background.png"), // BOTTOM_PANEL ("res/images/songmenu/bottom-panel-background.png"), // MAP_HEADER ("res/images/songmenu/map-header-background.png"), // // circles // SELECTED_DIFFICULTY ("res/images/songmenu/selected-difficulty-mark.png"), // AVAILABLE_DIFFICULTY ("res/images/songmenu/available-difficulty-mark.png"), // UNAVAILABLE_DIFFICULTY ("res/images/songmenu/unavailable-difficulty-mark.png"), // // // Square mode backgrounds // BUTTONS_BACKGROUND ("res/images/squaremode/buttons-background.png"), // COMBO_BACKGROUND ("res/images/squaremode/combo-background.png"), // HP_BACKGROUND ("res/images/squaremode/hp-background.png"), // STATS_BACKGROUND ("res/images/squaremode/stats-background.png"), // // // Square mode buttons // GREEN_BUTTON ("res/images/squaremode/green-button.png"), // PINK_BUTTON ("res/images/squaremode/pink-button.png"); // // private String path; // private Integer texture; // // /** // * Basic image // * @param path to the image // */ // Images(String path) { // this.path = path; // texture = null; // } // // /** // * @return OpenGL texture // */ // public int getTexture() { // if(texture == null) { // texture = Resources.getTexture(path); // } // return texture; // } // // public static void whatDoesNicktaelSaid() { // Logger.getLogger("Nickta").log(Level.WARNING, "THIS DANK CODE IS 2COOL4U"); // MAJESTIC GLORIOUS // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Sprite.java // public class Sprite { // // private Integer texture; // // public Sprite(Integer texture) { // this.texture = texture; // } // // public Integer getTexture() { // return texture; // } // // public void setTexture(int texture) { // this.texture = texture; // } // // public void draw(float x, float y, float width, float height) { // if(texture != null) { // glPushMatrix(); // glTranslatef(x, y, 0.0f); // glColor3f(1.0f, 1.0f, 1.0f); // glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, texture); // glBegin(GL_QUADS); // glTexCoord2f(0.0f, 0.0f); // glVertex3f(0.0f, height, 0.0f); // glTexCoord2f(1.0f, 0.0f); // glVertex3f(width, height, 0.0f); // glTexCoord2f(1.0f, 1.0f); // glVertex3f(width, 0.0f, 0.0f); // glTexCoord2f(0.0f, 1.0f); // glVertex3f(0.0f, 0.0f, 0.0f); // glEnd(); // glDisable(GL_TEXTURE_2D); // glPopMatrix(); // } // } // // }
import org.flamierawieo.x00FA9A.client.Images; import org.flamierawieo.x00FA9A.client.graphics.Sprite; import org.lwjgl.glfw.*; import java.util.Stack; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
package org.flamierawieo.x00FA9A.client.ui; public class ViewManager { private static float mouseRelativePosX; private static float mouseRelativePosY; private static Cursor cursor; private static int windowWidth, windowHeight; private static Stack<View> viewStack; private static View currentView; private static GLFWWindowSizeCallback glfwWindowSizeCallback; private static GLFWKeyCallback glfwKeyCallback; private static GLFWCursorPosCallback glfwCursorPosCallback; private static GLFWMouseButtonCallback glfwMouseButtonCallback; private static GLFWScrollCallback glfwScrollCallback; private static float aspect;
// Path: src/main/java/org/flamierawieo/x00FA9A/client/Images.java // public enum Images { // // CURSOR_IMAGE ("res/images/cursor.png"), // BASIC_BACKGROUND ("res/images/background.png"), // TEST ("custom/beatmaps/6fb2cf0d Truxton - Alexandrian Ricochet Sphere/background.png"), // // // Start menu and player widget // MENU_BUTTON ("res/images/startmenu/menu-buttons.png"), // PLAY ("res/images/playerwidget/play.png"), // PAUSE ("res/images/playerwidget/pause.png"), // // //Settings menu // SETTINGS_BACKGROUND ("res/images/settingsmenu/settings-background.png"), // SETTINGS_LINE ("res/images/settingsmenu/settings-line.png"), // // // Song menu // SONG_LIST_BACKGROUND ("res/images/songmenu/song-list-background.png"), // ACTIVE_SONG_BACKGROUND ("res/images/songmenu/active-song-background.png"), // SEARCH_BACKGROUND ("res/images/songmenu/search-background.png"), // SELECT_MODE ("res/images/songmenu/logo-background.png"), // BOTTOM_PANEL ("res/images/songmenu/bottom-panel-background.png"), // MAP_HEADER ("res/images/songmenu/map-header-background.png"), // // circles // SELECTED_DIFFICULTY ("res/images/songmenu/selected-difficulty-mark.png"), // AVAILABLE_DIFFICULTY ("res/images/songmenu/available-difficulty-mark.png"), // UNAVAILABLE_DIFFICULTY ("res/images/songmenu/unavailable-difficulty-mark.png"), // // // Square mode backgrounds // BUTTONS_BACKGROUND ("res/images/squaremode/buttons-background.png"), // COMBO_BACKGROUND ("res/images/squaremode/combo-background.png"), // HP_BACKGROUND ("res/images/squaremode/hp-background.png"), // STATS_BACKGROUND ("res/images/squaremode/stats-background.png"), // // // Square mode buttons // GREEN_BUTTON ("res/images/squaremode/green-button.png"), // PINK_BUTTON ("res/images/squaremode/pink-button.png"); // // private String path; // private Integer texture; // // /** // * Basic image // * @param path to the image // */ // Images(String path) { // this.path = path; // texture = null; // } // // /** // * @return OpenGL texture // */ // public int getTexture() { // if(texture == null) { // texture = Resources.getTexture(path); // } // return texture; // } // // public static void whatDoesNicktaelSaid() { // Logger.getLogger("Nickta").log(Level.WARNING, "THIS DANK CODE IS 2COOL4U"); // MAJESTIC GLORIOUS // } // // } // // Path: src/main/java/org/flamierawieo/x00FA9A/client/graphics/Sprite.java // public class Sprite { // // private Integer texture; // // public Sprite(Integer texture) { // this.texture = texture; // } // // public Integer getTexture() { // return texture; // } // // public void setTexture(int texture) { // this.texture = texture; // } // // public void draw(float x, float y, float width, float height) { // if(texture != null) { // glPushMatrix(); // glTranslatef(x, y, 0.0f); // glColor3f(1.0f, 1.0f, 1.0f); // glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, texture); // glBegin(GL_QUADS); // glTexCoord2f(0.0f, 0.0f); // glVertex3f(0.0f, height, 0.0f); // glTexCoord2f(1.0f, 0.0f); // glVertex3f(width, height, 0.0f); // glTexCoord2f(1.0f, 1.0f); // glVertex3f(width, 0.0f, 0.0f); // glTexCoord2f(0.0f, 1.0f); // glVertex3f(0.0f, 0.0f, 0.0f); // glEnd(); // glDisable(GL_TEXTURE_2D); // glPopMatrix(); // } // } // // } // Path: src/main/java/org/flamierawieo/x00FA9A/client/ui/ViewManager.java import org.flamierawieo.x00FA9A.client.Images; import org.flamierawieo.x00FA9A.client.graphics.Sprite; import org.lwjgl.glfw.*; import java.util.Stack; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; package org.flamierawieo.x00FA9A.client.ui; public class ViewManager { private static float mouseRelativePosX; private static float mouseRelativePosY; private static Cursor cursor; private static int windowWidth, windowHeight; private static Stack<View> viewStack; private static View currentView; private static GLFWWindowSizeCallback glfwWindowSizeCallback; private static GLFWKeyCallback glfwKeyCallback; private static GLFWCursorPosCallback glfwCursorPosCallback; private static GLFWMouseButtonCallback glfwMouseButtonCallback; private static GLFWScrollCallback glfwScrollCallback; private static float aspect;
private static Sprite gameBackground;
patrickfav/uber-adb-tools
src/test/java/at/favre/tools/uberadb/parser/FileArgParserTest.java
// Path: src/main/java/at/favre/tools/uberadb/ui/FileArgParser.java // public class FileArgParser { // // public List<File> parseAndSortUniqueFilesNonRecursive(String[] files, String extensionFilter) { // if (files == null) { // throw new IllegalArgumentException("input files must not be null"); // } // // if (files.length == 0) { // return Collections.emptyList(); // } // // Set<File> fileSet = new HashSet<>(); // // for (String file : files) { // File apkFile = new File(file); // // if (apkFile.exists() && apkFile.isDirectory()) { // for (File dirFile : apkFile.listFiles()) { // if (isCorrectFile(dirFile, extensionFilter)) { // fileSet.add(dirFile); // } // } // } else if (isCorrectFile(apkFile, extensionFilter)) { // fileSet.add(apkFile); // } else { // throw new IllegalArgumentException("provided apk path or file '" + file + "' does not exist"); // } // } // // List<File> resultList = new ArrayList<>(fileSet); // Collections.sort(resultList); // return resultList; // } // // private static boolean isCorrectFile(File f, String extensionFilter) { // if (f != null && f.exists() && f.isFile()) { // return FileUtil.getFileExtension(f).equalsIgnoreCase(extensionFilter); // } // return false; // } // }
import at.favre.tools.uberadb.ui.FileArgParser; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import static junit.framework.TestCase.assertEquals;
package at.favre.tools.uberadb.parser; public class FileArgParserTest { File signedFolder; List<File> sortedSinged; private String extFilter = "apk"; @Before public void setUp() throws Exception { signedFolder = new File(getClass().getClassLoader().getResource("apks").toURI().getPath()); sortedSinged = Arrays.asList(signedFolder.listFiles()); Collections.sort(sortedSinged); } @Test public void testSingleFolder() throws Exception {
// Path: src/main/java/at/favre/tools/uberadb/ui/FileArgParser.java // public class FileArgParser { // // public List<File> parseAndSortUniqueFilesNonRecursive(String[] files, String extensionFilter) { // if (files == null) { // throw new IllegalArgumentException("input files must not be null"); // } // // if (files.length == 0) { // return Collections.emptyList(); // } // // Set<File> fileSet = new HashSet<>(); // // for (String file : files) { // File apkFile = new File(file); // // if (apkFile.exists() && apkFile.isDirectory()) { // for (File dirFile : apkFile.listFiles()) { // if (isCorrectFile(dirFile, extensionFilter)) { // fileSet.add(dirFile); // } // } // } else if (isCorrectFile(apkFile, extensionFilter)) { // fileSet.add(apkFile); // } else { // throw new IllegalArgumentException("provided apk path or file '" + file + "' does not exist"); // } // } // // List<File> resultList = new ArrayList<>(fileSet); // Collections.sort(resultList); // return resultList; // } // // private static boolean isCorrectFile(File f, String extensionFilter) { // if (f != null && f.exists() && f.isFile()) { // return FileUtil.getFileExtension(f).equalsIgnoreCase(extensionFilter); // } // return false; // } // } // Path: src/test/java/at/favre/tools/uberadb/parser/FileArgParserTest.java import at.favre.tools.uberadb.ui.FileArgParser; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import static junit.framework.TestCase.assertEquals; package at.favre.tools.uberadb.parser; public class FileArgParserTest { File signedFolder; List<File> sortedSinged; private String extFilter = "apk"; @Before public void setUp() throws Exception { signedFolder = new File(getClass().getClassLoader().getResource("apks").toURI().getPath()); sortedSinged = Arrays.asList(signedFolder.listFiles()); Collections.sort(sortedSinged); } @Test public void testSingleFolder() throws Exception {
List<File> result = new FileArgParser().parseAndSortUniqueFilesNonRecursive(new String[]{signedFolder.getAbsolutePath()}, extFilter);
patrickfav/uber-adb-tools
src/main/java/at/favre/tools/uberadb/ui/FileArgParser.java
// Path: src/main/java/at/favre/tools/uberadb/util/FileUtil.java // public final class FileUtil { // // private FileUtil() { // } // // public static String getFileExtension(File file) { // if (file == null) { // return ""; // } // return file.getName().substring(file.getName().lastIndexOf(".") + 1); // } // // public static String getFileNameWithoutExtension(File file) { // String fileName = file.getName(); // int pos = fileName.lastIndexOf("."); // if (pos > 0) { // fileName = fileName.substring(0, pos); // } // return fileName; // } // // public static String createChecksum(File file, String shaAlgo) { // try { // InputStream fis = new FileInputStream(file); // byte[] buffer = new byte[1024]; // MessageDigest complete = MessageDigest.getInstance(shaAlgo); // int numRead; // // do { // numRead = fis.read(buffer); // if (numRead > 0) { // complete.update(buffer, 0, numRead); // } // } while (numRead != -1); // // fis.close(); // return new BigInteger(1, complete.digest()).toString(16).toLowerCase(); // } catch (Exception e) { // throw new IllegalStateException("could not create checksum for " + file + " and algo " + shaAlgo + ": " + e.getMessage(), e); // } // } // // public static void removeRecursive(Path path) { // try { // Files.walkFileTree(path, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } else { // throw exc; // } // } // }); // } catch (Exception e) { // throw new IllegalStateException("could not delete " + path + ": " + e.getMessage(), e); // } // } // // public static String getFileSizeMb(File file) { // try { // DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); // df.applyPattern("0.0#"); // long fileSizeInBytes = file.length(); // return df.format(fileSizeInBytes / (1024.0f * 1024.0f)) + " MiB"; // } catch (Exception e) { // return "<null>"; // } // } // }
import at.favre.tools.uberadb.util.FileUtil; import java.io.File; import java.util.*;
/* * * * Copyright 2016 Patrick Favre-Bulle * * * * 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 at.favre.tools.uberadb.ui; /** * Parses and checks the file input argument */ public class FileArgParser { public List<File> parseAndSortUniqueFilesNonRecursive(String[] files, String extensionFilter) { if (files == null) { throw new IllegalArgumentException("input files must not be null"); } if (files.length == 0) { return Collections.emptyList(); } Set<File> fileSet = new HashSet<>(); for (String file : files) { File apkFile = new File(file); if (apkFile.exists() && apkFile.isDirectory()) { for (File dirFile : apkFile.listFiles()) { if (isCorrectFile(dirFile, extensionFilter)) { fileSet.add(dirFile); } } } else if (isCorrectFile(apkFile, extensionFilter)) { fileSet.add(apkFile); } else { throw new IllegalArgumentException("provided apk path or file '" + file + "' does not exist"); } } List<File> resultList = new ArrayList<>(fileSet); Collections.sort(resultList); return resultList; } private static boolean isCorrectFile(File f, String extensionFilter) { if (f != null && f.exists() && f.isFile()) {
// Path: src/main/java/at/favre/tools/uberadb/util/FileUtil.java // public final class FileUtil { // // private FileUtil() { // } // // public static String getFileExtension(File file) { // if (file == null) { // return ""; // } // return file.getName().substring(file.getName().lastIndexOf(".") + 1); // } // // public static String getFileNameWithoutExtension(File file) { // String fileName = file.getName(); // int pos = fileName.lastIndexOf("."); // if (pos > 0) { // fileName = fileName.substring(0, pos); // } // return fileName; // } // // public static String createChecksum(File file, String shaAlgo) { // try { // InputStream fis = new FileInputStream(file); // byte[] buffer = new byte[1024]; // MessageDigest complete = MessageDigest.getInstance(shaAlgo); // int numRead; // // do { // numRead = fis.read(buffer); // if (numRead > 0) { // complete.update(buffer, 0, numRead); // } // } while (numRead != -1); // // fis.close(); // return new BigInteger(1, complete.digest()).toString(16).toLowerCase(); // } catch (Exception e) { // throw new IllegalStateException("could not create checksum for " + file + " and algo " + shaAlgo + ": " + e.getMessage(), e); // } // } // // public static void removeRecursive(Path path) { // try { // Files.walkFileTree(path, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } else { // throw exc; // } // } // }); // } catch (Exception e) { // throw new IllegalStateException("could not delete " + path + ": " + e.getMessage(), e); // } // } // // public static String getFileSizeMb(File file) { // try { // DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); // df.applyPattern("0.0#"); // long fileSizeInBytes = file.length(); // return df.format(fileSizeInBytes / (1024.0f * 1024.0f)) + " MiB"; // } catch (Exception e) { // return "<null>"; // } // } // } // Path: src/main/java/at/favre/tools/uberadb/ui/FileArgParser.java import at.favre.tools.uberadb.util.FileUtil; import java.io.File; import java.util.*; /* * * * Copyright 2016 Patrick Favre-Bulle * * * * 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 at.favre.tools.uberadb.ui; /** * Parses and checks the file input argument */ public class FileArgParser { public List<File> parseAndSortUniqueFilesNonRecursive(String[] files, String extensionFilter) { if (files == null) { throw new IllegalArgumentException("input files must not be null"); } if (files.length == 0) { return Collections.emptyList(); } Set<File> fileSet = new HashSet<>(); for (String file : files) { File apkFile = new File(file); if (apkFile.exists() && apkFile.isDirectory()) { for (File dirFile : apkFile.listFiles()) { if (isCorrectFile(dirFile, extensionFilter)) { fileSet.add(dirFile); } } } else if (isCorrectFile(apkFile, extensionFilter)) { fileSet.add(apkFile); } else { throw new IllegalArgumentException("provided apk path or file '" + file + "' does not exist"); } } List<File> resultList = new ArrayList<>(fileSet); Collections.sort(resultList); return resultList; } private static boolean isCorrectFile(File f, String extensionFilter) { if (f != null && f.exists() && f.isFile()) {
return FileUtil.getFileExtension(f).equalsIgnoreCase(extensionFilter);
patrickfav/uber-adb-tools
src/test/java/at/favre/tools/uberadb/util/CmdUtilTest.java
// Path: src/test/java/at/favre/tools/uberadb/MockAdbCmdProvider.java // public class MockAdbCmdProvider implements CmdProvider { // private List<AdbDevice> devices = Collections.emptyList(); // private List<String> installedPackages = Collections.emptyList(); // private boolean returnsSuccess = true; // private boolean canRunCmd = true; // private List<Result> history = new ArrayList<>(); // // public MockAdbCmdProvider(List<AdbDevice> devices, List<String> installedPackages, boolean returnsSuccess) { // this.devices = devices; // this.installedPackages = installedPackages; // this.returnsSuccess = returnsSuccess; // } // // public MockAdbCmdProvider(boolean canRunCmd) { // this.canRunCmd = canRunCmd; // } // // @Override // public Result runCmd(String[] args) { // String flatCmd = CmdUtil.concat(args, " "); // StringBuilder out = new StringBuilder(); // // if (flatCmd.contains("devices -l")) { // out.append("List of devices attached\n"); // for (AdbDevice device : devices) { // out.append(device.serial).append("\tdevice product:").append(device.product).append(" model:").append(device.model).append(" device:").append(device.product).append("\n"); // } // } else if (flatCmd.contains("pm list packages")) { // for (String installedPackage : installedPackages) { // out.append("package:/data/app/").append(installedPackage).append("/base.apk=").append(installedPackage).append("\n"); // } // } else if (flatCmd.contains("uninstall")) { // if (returnsSuccess) { // out.append("Success"); // } else { // out.append("Failure [MOCK-ERROR-UNINSTALL]"); // } // } else if (flatCmd.contains("install")) { // if (returnsSuccess) { // out.append("Success"); // } else { // out.append("Failure [MOCK-ERROR-INSTALL]"); // } // } // Result r = new Result(out.toString(), null, args, 0); // history.add(r); // return r; // } // // @Override // public boolean canRunCmd(String[] cmd) { // return canRunCmd; // } // // @Override // public List<Result> getHistory() { // return history; // } // // public int deviceCount() { // return devices.size(); // } // // public int installedCount() { // return installedPackages.size(); // } // }
import at.favre.tools.uberadb.MockAdbCmdProvider; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
package at.favre.tools.uberadb.util; public class CmdUtilTest { @Test public void testOs() { assertNotNull(CmdUtil.getOsType()); } @Test public void testPathShouldBeNull() { assertNull(CmdUtil.checkAndGetFromPATHEnvVar(
// Path: src/test/java/at/favre/tools/uberadb/MockAdbCmdProvider.java // public class MockAdbCmdProvider implements CmdProvider { // private List<AdbDevice> devices = Collections.emptyList(); // private List<String> installedPackages = Collections.emptyList(); // private boolean returnsSuccess = true; // private boolean canRunCmd = true; // private List<Result> history = new ArrayList<>(); // // public MockAdbCmdProvider(List<AdbDevice> devices, List<String> installedPackages, boolean returnsSuccess) { // this.devices = devices; // this.installedPackages = installedPackages; // this.returnsSuccess = returnsSuccess; // } // // public MockAdbCmdProvider(boolean canRunCmd) { // this.canRunCmd = canRunCmd; // } // // @Override // public Result runCmd(String[] args) { // String flatCmd = CmdUtil.concat(args, " "); // StringBuilder out = new StringBuilder(); // // if (flatCmd.contains("devices -l")) { // out.append("List of devices attached\n"); // for (AdbDevice device : devices) { // out.append(device.serial).append("\tdevice product:").append(device.product).append(" model:").append(device.model).append(" device:").append(device.product).append("\n"); // } // } else if (flatCmd.contains("pm list packages")) { // for (String installedPackage : installedPackages) { // out.append("package:/data/app/").append(installedPackage).append("/base.apk=").append(installedPackage).append("\n"); // } // } else if (flatCmd.contains("uninstall")) { // if (returnsSuccess) { // out.append("Success"); // } else { // out.append("Failure [MOCK-ERROR-UNINSTALL]"); // } // } else if (flatCmd.contains("install")) { // if (returnsSuccess) { // out.append("Success"); // } else { // out.append("Failure [MOCK-ERROR-INSTALL]"); // } // } // Result r = new Result(out.toString(), null, args, 0); // history.add(r); // return r; // } // // @Override // public boolean canRunCmd(String[] cmd) { // return canRunCmd; // } // // @Override // public List<Result> getHistory() { // return history; // } // // public int deviceCount() { // return devices.size(); // } // // public int installedCount() { // return installedPackages.size(); // } // } // Path: src/test/java/at/favre/tools/uberadb/util/CmdUtilTest.java import at.favre.tools.uberadb.MockAdbCmdProvider; import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; package at.favre.tools.uberadb.util; public class CmdUtilTest { @Test public void testOs() { assertNotNull(CmdUtil.getOsType()); } @Test public void testPathShouldBeNull() { assertNull(CmdUtil.checkAndGetFromPATHEnvVar(
new MockAdbCmdProvider(false)
patrickfav/uber-adb-tools
src/main/java/at/favre/tools/uberadb/CmdProvider.java
// Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // }
import at.favre.tools.uberadb.util.CmdUtil; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;
exception = e; } Result r = new Result(logStringBuilder.toString(), exception, args, exitValue); history.add(r); return r; } @Override public boolean canRunCmd(String[] cmd) { Result result = runCmd(cmd); history.add(result); return result.exception == null; } @Override public List<Result> getHistory() { return history; } } class Result { public final Exception exception; public final String out; public final String cmd; public final int exitValue; public Result(String out, Exception exception, String[] cmd, int exitValue) { this.out = out; this.exception = exception;
// Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // } // Path: src/main/java/at/favre/tools/uberadb/CmdProvider.java import at.favre.tools.uberadb.util.CmdUtil; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; exception = e; } Result r = new Result(logStringBuilder.toString(), exception, args, exitValue); history.add(r); return r; } @Override public boolean canRunCmd(String[] cmd) { Result result = runCmd(cmd); history.add(result); return result.exception == null; } @Override public List<Result> getHistory() { return history; } } class Result { public final Exception exception; public final String out; public final String cmd; public final int exitValue; public Result(String out, Exception exception, String[] cmd, int exitValue) { this.out = out; this.exception = exception;
this.cmd = CmdUtil.concat(cmd, " ");
patrickfav/uber-adb-tools
src/test/java/at/favre/tools/uberadb/MockAdbCmdProvider.java
// Path: src/main/java/at/favre/tools/uberadb/parser/AdbDevice.java // public class AdbDevice { // public enum Status { // OK, OFFLINE, UNAUTHORIZED, BOOTLOADER, UNKNOWN // } // // public final String serial; // public final Status status; // public final String model; // public final String product; // public final boolean isEmulator; // // public AdbDevice(String serial, Status status, String model, String product, boolean isEmulator) { // this.serial = serial; // this.status = status; // this.model = model; // this.product = product; // this.isEmulator = isEmulator; // } // // @Override // public String toString() { // return "AdbDevice{" + // "serial='" + serial + '\'' + // ", status=" + status + // ", model='" + model + '\'' + // ", product='" + product + '\'' + // ", isEmulator=" + isEmulator + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AdbDevice adbDevice = (AdbDevice) o; // // if (isEmulator != adbDevice.isEmulator) return false; // if (serial != null ? !serial.equals(adbDevice.serial) : adbDevice.serial != null) return false; // if (status != adbDevice.status) return false; // if (model != null ? !model.equals(adbDevice.model) : adbDevice.model != null) return false; // return product != null ? product.equals(adbDevice.product) : adbDevice.product == null; // // } // // @Override // public int hashCode() { // int result = serial != null ? serial.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // result = 31 * result + (model != null ? model.hashCode() : 0); // result = 31 * result + (product != null ? product.hashCode() : 0); // result = 31 * result + (isEmulator ? 1 : 0); // return result; // } // } // // Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // }
import at.favre.tools.uberadb.parser.AdbDevice; import at.favre.tools.uberadb.util.CmdUtil; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package at.favre.tools.uberadb; public class MockAdbCmdProvider implements CmdProvider { private List<AdbDevice> devices = Collections.emptyList(); private List<String> installedPackages = Collections.emptyList(); private boolean returnsSuccess = true; private boolean canRunCmd = true; private List<Result> history = new ArrayList<>(); public MockAdbCmdProvider(List<AdbDevice> devices, List<String> installedPackages, boolean returnsSuccess) { this.devices = devices; this.installedPackages = installedPackages; this.returnsSuccess = returnsSuccess; } public MockAdbCmdProvider(boolean canRunCmd) { this.canRunCmd = canRunCmd; } @Override public Result runCmd(String[] args) {
// Path: src/main/java/at/favre/tools/uberadb/parser/AdbDevice.java // public class AdbDevice { // public enum Status { // OK, OFFLINE, UNAUTHORIZED, BOOTLOADER, UNKNOWN // } // // public final String serial; // public final Status status; // public final String model; // public final String product; // public final boolean isEmulator; // // public AdbDevice(String serial, Status status, String model, String product, boolean isEmulator) { // this.serial = serial; // this.status = status; // this.model = model; // this.product = product; // this.isEmulator = isEmulator; // } // // @Override // public String toString() { // return "AdbDevice{" + // "serial='" + serial + '\'' + // ", status=" + status + // ", model='" + model + '\'' + // ", product='" + product + '\'' + // ", isEmulator=" + isEmulator + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AdbDevice adbDevice = (AdbDevice) o; // // if (isEmulator != adbDevice.isEmulator) return false; // if (serial != null ? !serial.equals(adbDevice.serial) : adbDevice.serial != null) return false; // if (status != adbDevice.status) return false; // if (model != null ? !model.equals(adbDevice.model) : adbDevice.model != null) return false; // return product != null ? product.equals(adbDevice.product) : adbDevice.product == null; // // } // // @Override // public int hashCode() { // int result = serial != null ? serial.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // result = 31 * result + (model != null ? model.hashCode() : 0); // result = 31 * result + (product != null ? product.hashCode() : 0); // result = 31 * result + (isEmulator ? 1 : 0); // return result; // } // } // // Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // } // Path: src/test/java/at/favre/tools/uberadb/MockAdbCmdProvider.java import at.favre.tools.uberadb.parser.AdbDevice; import at.favre.tools.uberadb.util.CmdUtil; import java.util.ArrayList; import java.util.Collections; import java.util.List; package at.favre.tools.uberadb; public class MockAdbCmdProvider implements CmdProvider { private List<AdbDevice> devices = Collections.emptyList(); private List<String> installedPackages = Collections.emptyList(); private boolean returnsSuccess = true; private boolean canRunCmd = true; private List<Result> history = new ArrayList<>(); public MockAdbCmdProvider(List<AdbDevice> devices, List<String> installedPackages, boolean returnsSuccess) { this.devices = devices; this.installedPackages = installedPackages; this.returnsSuccess = returnsSuccess; } public MockAdbCmdProvider(boolean canRunCmd) { this.canRunCmd = canRunCmd; } @Override public Result runCmd(String[] args) {
String flatCmd = CmdUtil.concat(args, " ");
patrickfav/uber-adb-tools
src/main/java/at/favre/tools/uberadb/AdbLocationFinderImpl.java
// Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // }
import at.favre.tools.uberadb.util.CmdUtil; import java.io.File;
/* * * * Copyright 2016 Patrick Favre-Bulle * * * * 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 at.favre.tools.uberadb; public class AdbLocationFinderImpl implements AdbLocationFinder { private static final String WIN_DEFAULT_SDK = "\\AppData\\Local\\Android\\sdk\\platform-tools\\adb.exe"; private static final String WIN_DEFAULT_ANDROID_HOME = "\\platform-tools\\adb.exe"; private static final String[] MAC_DEFAULT = new String[]{"/usr/local/opt/android-sdk/platform-tools/adb"}; private static final String MAC_DEFAULT_HOME = "/Library/Android/sdk/platform-tools/adb"; private static final String MAC_DEFAULT_ANDROID_HOME = "/platform-tools/adb"; private static final String[] LINUX_DEFAULT = MAC_DEFAULT; private static final String LINUX_DEFAULT_ANDROID_HOME = MAC_DEFAULT_ANDROID_HOME; private static final String LINUX_DEFAULT_2 = "/Android/Sdk/platform-tools/adb"; @Override public LocationResult find(CmdProvider cmdProvider, String customPath) { String osName = System.getProperty("os.name").toLowerCase(); if (customPath != null && new File(customPath).exists() && cmdProvider.canRunCmd(new String[]{customPath})) { return new LocationResult(Location.CUSTOM, new String[]{customPath}); }
// Path: src/main/java/at/favre/tools/uberadb/util/CmdUtil.java // public final class CmdUtil { // // private CmdUtil() { // } // // public static <T> T[] concat(T[] first, T[] second) { // T[] result = Arrays.copyOf(first, first.length + second.length); // System.arraycopy(second, 0, result, first.length, second.length); // return result; // } // // public static File checkAndGetFromPATHEnvVar(CmdProvider provider, final String matchesExecutable) { // String pathEnv = System.getenv("PATH"); // if (pathEnv != null) { // String[] pathParts = pathEnv.split(File.pathSeparator); // for (String pathPart : pathParts) { // File pathFile = new File(pathPart); // // if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) { // return pathFile; // } else if (pathFile.isDirectory()) { // File[] matchedFiles = pathFile.listFiles(new FileFilter() { // @Override // public boolean accept(File pathname) { // return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable); // } // }); // // if (matchedFiles != null) { // for (File matchedFile : matchedFiles) { // if (provider.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) { // return matchedFile; // } // } // } // } // } // } // return null; // } // // public static OS getOsType() { // String osName = System.getProperty("os.name").toLowerCase(); // // if (osName.contains("win")) { // return OS.WIN; // } // if (osName.contains("mac")) { // return OS.MAC; // } // // return OS._NIX; // } // // public enum OS { // WIN, MAC, _NIX // } // // public static String concat(String[] array, String separator) { // StringBuilder sb = new StringBuilder(); // String sep = ""; // for (String s : array) { // sb.append(sep).append(s); // sep = separator; // } // return sb.toString(); // } // // public static String jarVersion() { // return AdbTool.class.getPackage().getImplementationVersion(); // } // } // Path: src/main/java/at/favre/tools/uberadb/AdbLocationFinderImpl.java import at.favre.tools.uberadb.util.CmdUtil; import java.io.File; /* * * * Copyright 2016 Patrick Favre-Bulle * * * * 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 at.favre.tools.uberadb; public class AdbLocationFinderImpl implements AdbLocationFinder { private static final String WIN_DEFAULT_SDK = "\\AppData\\Local\\Android\\sdk\\platform-tools\\adb.exe"; private static final String WIN_DEFAULT_ANDROID_HOME = "\\platform-tools\\adb.exe"; private static final String[] MAC_DEFAULT = new String[]{"/usr/local/opt/android-sdk/platform-tools/adb"}; private static final String MAC_DEFAULT_HOME = "/Library/Android/sdk/platform-tools/adb"; private static final String MAC_DEFAULT_ANDROID_HOME = "/platform-tools/adb"; private static final String[] LINUX_DEFAULT = MAC_DEFAULT; private static final String LINUX_DEFAULT_ANDROID_HOME = MAC_DEFAULT_ANDROID_HOME; private static final String LINUX_DEFAULT_2 = "/Android/Sdk/platform-tools/adb"; @Override public LocationResult find(CmdProvider cmdProvider, String customPath) { String osName = System.getProperty("os.name").toLowerCase(); if (customPath != null && new File(customPath).exists() && cmdProvider.canRunCmd(new String[]{customPath})) { return new LocationResult(Location.CUSTOM, new String[]{customPath}); }
File pathAdbExe = CmdUtil.checkAndGetFromPATHEnvVar(cmdProvider, "adb");
wmora/openfeed
app/src/main/java/com/williammora/openfeed/fragments/RecentSearchResultsFragment.java
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // }
import com.squareup.otto.Subscribe; import com.williammora.openfeed.events.TwitterEvents; import twitter4j.Query;
package com.williammora.openfeed.fragments; public class RecentSearchResultsFragment extends SearchResultsFragment { public static final String TAG = RecentSearchResultsFragment.class.getSimpleName(); @Override protected Query.ResultType getResultType() { return Query.ResultType.recent; } @Subscribe
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // Path: app/src/main/java/com/williammora/openfeed/fragments/RecentSearchResultsFragment.java import com.squareup.otto.Subscribe; import com.williammora.openfeed.events.TwitterEvents; import twitter4j.Query; package com.williammora.openfeed.fragments; public class RecentSearchResultsFragment extends SearchResultsFragment { public static final String TAG = RecentSearchResultsFragment.class.getSimpleName(); @Override protected Query.ResultType getResultType() { return Query.ResultType.recent; } @Subscribe
public void onSearchEvent(TwitterEvents.SearchEvent event) {
wmora/openfeed
app/src/main/java/com/williammora/openfeed/fragments/OpenFeedFragment.java
// Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // }
import android.app.Fragment; import com.williammora.openfeed.utils.BusProvider;
package com.williammora.openfeed.fragments; public abstract class OpenFeedFragment extends Fragment { @Override public void onResume() { super.onResume();
// Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // Path: app/src/main/java/com/williammora/openfeed/fragments/OpenFeedFragment.java import android.app.Fragment; import com.williammora.openfeed.utils.BusProvider; package com.williammora.openfeed.fragments; public abstract class OpenFeedFragment extends Fragment { @Override public void onResume() { super.onResume();
BusProvider.getInstance().register(this);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/activities/OpenFeedActivity.java
// Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // }
import android.app.Activity; import com.williammora.openfeed.utils.BusProvider;
package com.williammora.openfeed.activities; public abstract class OpenFeedActivity extends Activity { @Override protected void onResume() { super.onResume();
// Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // Path: app/src/main/java/com/williammora/openfeed/activities/OpenFeedActivity.java import android.app.Activity; import com.williammora.openfeed.utils.BusProvider; package com.williammora.openfeed.activities; public abstract class OpenFeedActivity extends Activity { @Override protected void onResume() { super.onResume();
BusProvider.getInstance().register(this);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/activities/UserActivity.java
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/UserFragment.java // public class UserFragment extends OpenFeedFragment { // // public static final String SAVED_USER = "SAVED_USER"; // // public interface UserFragmentListener { // public User getUser(); // // public String getUserScreenName(); // } // // private UserFragmentListener mListener; // private User mUser; // private View mView; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (savedInstanceState != null) { // mUser = (User) savedInstanceState.getSerializable(SAVED_USER); // } // mView = inflater.inflate(R.layout.fragment_user, container, false); // if (mUser != null) { // updateView(mUser); // } else { // loadUser(mListener.getUserScreenName()); // } // return mView; // } // // private void loadUser(String screenName) { // TwitterService.getInstance().showUser(screenName); // } // // public void updateView(User user) { // ImageView profileBanner = (ImageView) mView.findViewById(R.id.profile_banner); // Picasso.with(profileBanner.getContext()) // .load(user.getProfileBannerMobileRetinaURL()) // .transform(new ProfileBannerTransformation(profileBanner, user.getId())) // .placeholder(R.drawable.profile_banner) // .into(profileBanner); // ImageView profileImage = (ImageView) mView.findViewById(R.id.profile_image); // Picasso.with(mView.getContext()) // .load(user.getBiggerProfileImageURLHttps()) // .placeholder(R.drawable.image_loader_placeholder) // .error(R.drawable.image_loader_placeholder) // .into(profileImage); // TextView profileName = (TextView) mView.findViewById(R.id.profile_name); // profileName.setText(user.getName()); // TextView profileScreenName = (TextView) mView.findViewById(R.id.profile_screen_name); // profileScreenName.setText(UserUtils.getFullScreenName(user)); // mUser = user; // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (activity instanceof UserFragmentListener) { // mListener = (UserFragmentListener) activity; // if (mUser == null) { // mUser = mListener.getUser(); // } // } // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_USER, mUser); // super.onSaveInstanceState(outState); // } // // @Subscribe // public void onUserEvent(TwitterEvents.UserEvent event) { // updateView(event.getResult()); // } // }
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.UserFragment; import twitter4j.User;
protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mUser = (User) savedInstanceState.getSerializable(SAVED_USER); mScreenName = savedInstanceState.getString(SAVED_SCREEN_NAME, ""); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override public User getUser() { return mUser; } @Override public String getUserScreenName() { return mScreenName; } @Subscribe
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/UserFragment.java // public class UserFragment extends OpenFeedFragment { // // public static final String SAVED_USER = "SAVED_USER"; // // public interface UserFragmentListener { // public User getUser(); // // public String getUserScreenName(); // } // // private UserFragmentListener mListener; // private User mUser; // private View mView; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (savedInstanceState != null) { // mUser = (User) savedInstanceState.getSerializable(SAVED_USER); // } // mView = inflater.inflate(R.layout.fragment_user, container, false); // if (mUser != null) { // updateView(mUser); // } else { // loadUser(mListener.getUserScreenName()); // } // return mView; // } // // private void loadUser(String screenName) { // TwitterService.getInstance().showUser(screenName); // } // // public void updateView(User user) { // ImageView profileBanner = (ImageView) mView.findViewById(R.id.profile_banner); // Picasso.with(profileBanner.getContext()) // .load(user.getProfileBannerMobileRetinaURL()) // .transform(new ProfileBannerTransformation(profileBanner, user.getId())) // .placeholder(R.drawable.profile_banner) // .into(profileBanner); // ImageView profileImage = (ImageView) mView.findViewById(R.id.profile_image); // Picasso.with(mView.getContext()) // .load(user.getBiggerProfileImageURLHttps()) // .placeholder(R.drawable.image_loader_placeholder) // .error(R.drawable.image_loader_placeholder) // .into(profileImage); // TextView profileName = (TextView) mView.findViewById(R.id.profile_name); // profileName.setText(user.getName()); // TextView profileScreenName = (TextView) mView.findViewById(R.id.profile_screen_name); // profileScreenName.setText(UserUtils.getFullScreenName(user)); // mUser = user; // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (activity instanceof UserFragmentListener) { // mListener = (UserFragmentListener) activity; // if (mUser == null) { // mUser = mListener.getUser(); // } // } // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_USER, mUser); // super.onSaveInstanceState(outState); // } // // @Subscribe // public void onUserEvent(TwitterEvents.UserEvent event) { // updateView(event.getResult()); // } // } // Path: app/src/main/java/com/williammora/openfeed/activities/UserActivity.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.UserFragment; import twitter4j.User; protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mUser = (User) savedInstanceState.getSerializable(SAVED_USER); mScreenName = savedInstanceState.getString(SAVED_SCREEN_NAME, ""); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override public User getUser() { return mUser; } @Override public String getUserScreenName() { return mScreenName; } @Subscribe
public void onUserEvent(TwitterEvents.UserEvent event) {
wmora/openfeed
app/src/main/java/com/williammora/openfeed/listeners/OnComposeStatusButtonClickListener.java
// Path: app/src/main/java/com/williammora/openfeed/activities/ComposeStatusActivity.java // public class ComposeStatusActivity extends Activity // implements ComposeStatusFragment.ComposeStatusFragmentListener { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_status); // if (savedInstanceState == null) { // getFragmentManager().beginTransaction() // .add(R.id.container, new ComposeStatusFragment()) // .commit(); // } // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // switch (item.getItemId()) { // case android.R.id.home: // finish(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onStatusUpdateRequested() { // finish(); // } // }
import android.content.Intent; import android.view.View; import com.williammora.openfeed.activities.ComposeStatusActivity; import twitter4j.Status;
package com.williammora.openfeed.listeners; public class OnComposeStatusButtonClickListener implements View.OnClickListener { /** * Status that will be replied to */ private Status mStatus; public OnComposeStatusButtonClickListener() { this(null); } public OnComposeStatusButtonClickListener(Status status) { mStatus = status; } @Override public void onClick(View view) { Intent intent = new Intent();
// Path: app/src/main/java/com/williammora/openfeed/activities/ComposeStatusActivity.java // public class ComposeStatusActivity extends Activity // implements ComposeStatusFragment.ComposeStatusFragmentListener { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_status); // if (savedInstanceState == null) { // getFragmentManager().beginTransaction() // .add(R.id.container, new ComposeStatusFragment()) // .commit(); // } // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // switch (item.getItemId()) { // case android.R.id.home: // finish(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onStatusUpdateRequested() { // finish(); // } // } // Path: app/src/main/java/com/williammora/openfeed/listeners/OnComposeStatusButtonClickListener.java import android.content.Intent; import android.view.View; import com.williammora.openfeed.activities.ComposeStatusActivity; import twitter4j.Status; package com.williammora.openfeed.listeners; public class OnComposeStatusButtonClickListener implements View.OnClickListener { /** * Status that will be replied to */ private Status mStatus; public OnComposeStatusButtonClickListener() { this(null); } public OnComposeStatusButtonClickListener(Status status) { mStatus = status; } @Override public void onClick(View view) { Intent intent = new Intent();
intent.setClass(view.getContext(), ComposeStatusActivity.class);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/activities/SearchResultsActivity.java
// Path: app/src/main/java/com/williammora/openfeed/fragments/PopularSearchResultsFragment.java // public class PopularSearchResultsFragment extends SearchResultsFragment { // // public static final String TAG = PopularSearchResultsFragment.class.getSimpleName(); // // @Override // protected Query.ResultType getResultType() { // return Query.ResultType.popular; // } // // @Subscribe // public void onSearchEvent(TwitterEvents.SearchEvent event) { // super.onSearchEvent(event); // } // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/SearchResultsFragment.java // public abstract class SearchResultsFragment extends AbstractFeedFragment { // // public interface SearchResultsFragmentListener extends FeedFragmentListener { // public String getQuery(); // } // // private SearchResultsFragmentListener mListener; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!(activity instanceof SearchResultsFragmentListener)) { // throw new ClassCastException("Activity must implement SearchResultsFragmentListener"); // } // mListener = (SearchResultsFragmentListener) activity; // } // // @Override // protected void doRequest(Paging paging) { // Query query = new Query(); // query.setQuery(mListener.getQuery()); // query.setCount(paging.getCount()); // query.setMaxId(paging.getMaxId()); // query.setSinceId(paging.getSinceId()); // query.setResultType(getResultType()); // TwitterService.getInstance().search(query); // } // // public void onSearchEvent(TwitterEvents.SearchEvent event) { // Feed feed = new Feed(); // feed.setPaging(mPaging); // feed.setStatuses(event.getResult().getTweets()); // updateFeed(feed); // onRequestCompleted(); // } // // protected abstract Query.ResultType getResultType(); // // }
import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.williammora.openfeed.R; import com.williammora.openfeed.fragments.PopularSearchResultsFragment; import com.williammora.openfeed.fragments.SearchResultsFragment;
package com.williammora.openfeed.activities; public class SearchResultsActivity extends Activity implements SearchResultsFragment.SearchResultsFragmentListener { private static final String SAVED_QUERY = "SAVED_QUERY"; private static final String SAVED_SHOWING_GO_TO_TOP = "SAVED_SHOWING_GO_TO_TOP"; private Menu mMenu; private boolean mShowingGoToTop; private String mQuery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_results); if (savedInstanceState == null) { getFragmentManager().beginTransaction()
// Path: app/src/main/java/com/williammora/openfeed/fragments/PopularSearchResultsFragment.java // public class PopularSearchResultsFragment extends SearchResultsFragment { // // public static final String TAG = PopularSearchResultsFragment.class.getSimpleName(); // // @Override // protected Query.ResultType getResultType() { // return Query.ResultType.popular; // } // // @Subscribe // public void onSearchEvent(TwitterEvents.SearchEvent event) { // super.onSearchEvent(event); // } // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/SearchResultsFragment.java // public abstract class SearchResultsFragment extends AbstractFeedFragment { // // public interface SearchResultsFragmentListener extends FeedFragmentListener { // public String getQuery(); // } // // private SearchResultsFragmentListener mListener; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // if (!(activity instanceof SearchResultsFragmentListener)) { // throw new ClassCastException("Activity must implement SearchResultsFragmentListener"); // } // mListener = (SearchResultsFragmentListener) activity; // } // // @Override // protected void doRequest(Paging paging) { // Query query = new Query(); // query.setQuery(mListener.getQuery()); // query.setCount(paging.getCount()); // query.setMaxId(paging.getMaxId()); // query.setSinceId(paging.getSinceId()); // query.setResultType(getResultType()); // TwitterService.getInstance().search(query); // } // // public void onSearchEvent(TwitterEvents.SearchEvent event) { // Feed feed = new Feed(); // feed.setPaging(mPaging); // feed.setStatuses(event.getResult().getTweets()); // updateFeed(feed); // onRequestCompleted(); // } // // protected abstract Query.ResultType getResultType(); // // } // Path: app/src/main/java/com/williammora/openfeed/activities/SearchResultsActivity.java import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.williammora.openfeed.R; import com.williammora.openfeed.fragments.PopularSearchResultsFragment; import com.williammora.openfeed.fragments.SearchResultsFragment; package com.williammora.openfeed.activities; public class SearchResultsActivity extends Activity implements SearchResultsFragment.SearchResultsFragmentListener { private static final String SAVED_QUERY = "SAVED_QUERY"; private static final String SAVED_SHOWING_GO_TO_TOP = "SAVED_SHOWING_GO_TO_TOP"; private Menu mMenu; private boolean mShowingGoToTop; private String mQuery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_results); if (savedInstanceState == null) { getFragmentManager().beginTransaction()
.add(R.id.container, new PopularSearchResultsFragment(), PopularSearchResultsFragment.TAG)
wmora/openfeed
app/src/main/java/com/williammora/openfeed/activities/StatusActivity.java
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/StatusFragment.java // public class StatusFragment extends OpenFeedFragment { // // private static final String SAVED_STATUS = "SAVED_STATUS"; // // private StatusViewHolder mViewHolder; // private Status mStatus; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_status, container, false); // // if (savedInstanceState != null) { // mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS); // } else { // mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS); // } // // mViewHolder = new StatusViewHolder(view); // // return view; // } // // @Override // public void onResume() { // super.onResume(); // updateStatus(mStatus); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_STATUS, mStatus); // super.onSaveInstanceState(outState); // } // // private void updateStatus(Status status) { // mStatus = status; // mViewHolder.updateView(mStatus); // } // // @Subscribe // public void onStatusRetweeted(TwitterEvents.RetweetedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onStatusDestroyed(TwitterEvents.DestroyedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusCreated(TwitterEvents.CreatedFavoriteEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusDestroyed(TwitterEvents.DestroyedFavoriteEvent event) { // updateStatus(event.getResult()); // } // }
import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.StatusFragment; import twitter4j.Status;
package com.williammora.openfeed.activities; public class StatusActivity extends OpenFeedActivity { public static final String EXTRA_STATUS = "EXTRA_STATUS"; private static final String SAVED_STATUS = "SAVED_STATUS"; private Status mStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_status); if (savedInstanceState == null) { getFragmentManager().beginTransaction()
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/StatusFragment.java // public class StatusFragment extends OpenFeedFragment { // // private static final String SAVED_STATUS = "SAVED_STATUS"; // // private StatusViewHolder mViewHolder; // private Status mStatus; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_status, container, false); // // if (savedInstanceState != null) { // mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS); // } else { // mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS); // } // // mViewHolder = new StatusViewHolder(view); // // return view; // } // // @Override // public void onResume() { // super.onResume(); // updateStatus(mStatus); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_STATUS, mStatus); // super.onSaveInstanceState(outState); // } // // private void updateStatus(Status status) { // mStatus = status; // mViewHolder.updateView(mStatus); // } // // @Subscribe // public void onStatusRetweeted(TwitterEvents.RetweetedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onStatusDestroyed(TwitterEvents.DestroyedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusCreated(TwitterEvents.CreatedFavoriteEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusDestroyed(TwitterEvents.DestroyedFavoriteEvent event) { // updateStatus(event.getResult()); // } // } // Path: app/src/main/java/com/williammora/openfeed/activities/StatusActivity.java import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.StatusFragment; import twitter4j.Status; package com.williammora.openfeed.activities; public class StatusActivity extends OpenFeedActivity { public static final String EXTRA_STATUS = "EXTRA_STATUS"; private static final String SAVED_STATUS = "SAVED_STATUS"; private Status mStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_status); if (savedInstanceState == null) { getFragmentManager().beginTransaction()
.add(R.id.container, new StatusFragment())
wmora/openfeed
app/src/main/java/com/williammora/openfeed/activities/StatusActivity.java
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/StatusFragment.java // public class StatusFragment extends OpenFeedFragment { // // private static final String SAVED_STATUS = "SAVED_STATUS"; // // private StatusViewHolder mViewHolder; // private Status mStatus; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_status, container, false); // // if (savedInstanceState != null) { // mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS); // } else { // mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS); // } // // mViewHolder = new StatusViewHolder(view); // // return view; // } // // @Override // public void onResume() { // super.onResume(); // updateStatus(mStatus); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_STATUS, mStatus); // super.onSaveInstanceState(outState); // } // // private void updateStatus(Status status) { // mStatus = status; // mViewHolder.updateView(mStatus); // } // // @Subscribe // public void onStatusRetweeted(TwitterEvents.RetweetedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onStatusDestroyed(TwitterEvents.DestroyedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusCreated(TwitterEvents.CreatedFavoriteEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusDestroyed(TwitterEvents.DestroyedFavoriteEvent event) { // updateStatus(event.getResult()); // } // }
import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.StatusFragment; import twitter4j.Status;
outState.putSerializable(SAVED_STATUS, mStatus); super.onSaveInstanceState(outState); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: close(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { close(); } private void close() { Intent intent = new Intent(); intent.putExtra(EXTRA_STATUS, mStatus); setResult(RESULT_OK, intent); finish(); } @Subscribe
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/fragments/StatusFragment.java // public class StatusFragment extends OpenFeedFragment { // // private static final String SAVED_STATUS = "SAVED_STATUS"; // // private StatusViewHolder mViewHolder; // private Status mStatus; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_status, container, false); // // if (savedInstanceState != null) { // mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS); // } else { // mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS); // } // // mViewHolder = new StatusViewHolder(view); // // return view; // } // // @Override // public void onResume() { // super.onResume(); // updateStatus(mStatus); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_STATUS, mStatus); // super.onSaveInstanceState(outState); // } // // private void updateStatus(Status status) { // mStatus = status; // mViewHolder.updateView(mStatus); // } // // @Subscribe // public void onStatusRetweeted(TwitterEvents.RetweetedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onStatusDestroyed(TwitterEvents.DestroyedStatusEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusCreated(TwitterEvents.CreatedFavoriteEvent event) { // updateStatus(event.getResult()); // } // // @Subscribe // public void onFavoriteStatusDestroyed(TwitterEvents.DestroyedFavoriteEvent event) { // updateStatus(event.getResult()); // } // } // Path: app/src/main/java/com/williammora/openfeed/activities/StatusActivity.java import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.squareup.otto.Subscribe; import com.williammora.openfeed.R; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.fragments.StatusFragment; import twitter4j.Status; outState.putSerializable(SAVED_STATUS, mStatus); super.onSaveInstanceState(outState); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: close(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { close(); } private void close() { Intent intent = new Intent(); intent.putExtra(EXTRA_STATUS, mStatus); setResult(RESULT_OK, intent); finish(); } @Subscribe
public void onStatusRetweeted(TwitterEvents.RetweetedStatusEvent event) {
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
package com.williammora.openfeed.services; public class TwitterService { private static final String TAG = TwitterService.class.getSimpleName(); private static TwitterService ourInstance = new TwitterService(); private RequestToken requestToken; private Context context; private AsyncTwitter twitter; private boolean loaded; public static TwitterService getInstance() { return ourInstance; } private TwitterService() { } public void init() { if (loaded) { return; }
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // } // Path: app/src/main/java/com/williammora/openfeed/services/TwitterService.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; package com.williammora.openfeed.services; public class TwitterService { private static final String TAG = TwitterService.class.getSimpleName(); private static TwitterService ourInstance = new TwitterService(); private RequestToken requestToken; private Context context; private AsyncTwitter twitter; private boolean loaded; public static TwitterService getInstance() { return ourInstance; } private TwitterService() { } public void init() { if (loaded) { return; }
context = OpenFeed.getApplication().getApplicationContext();
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
package com.williammora.openfeed.services; public class TwitterService { private static final String TAG = TwitterService.class.getSimpleName(); private static TwitterService ourInstance = new TwitterService(); private RequestToken requestToken; private Context context; private AsyncTwitter twitter; private boolean loaded; public static TwitterService getInstance() { return ourInstance; } private TwitterService() { } public void init() { if (loaded) { return; } context = OpenFeed.getApplication().getApplicationContext(); twitter = new AsyncTwitterFactory().getInstance(); twitter.addListener(new TwitterListener()); twitter.setOAuthConsumer(getTwitterOauthKey(), getTwitterOauthSecret()); if (isSignedIn()) { twitter.setOAuthAccessToken(getAccessToken()); } loaded = true; } private SharedPreferences getSharedPreferences() {
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // } // Path: app/src/main/java/com/williammora/openfeed/services/TwitterService.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; package com.williammora.openfeed.services; public class TwitterService { private static final String TAG = TwitterService.class.getSimpleName(); private static TwitterService ourInstance = new TwitterService(); private RequestToken requestToken; private Context context; private AsyncTwitter twitter; private boolean loaded; public static TwitterService getInstance() { return ourInstance; } private TwitterService() { } public void init() { if (loaded) { return; } context = OpenFeed.getApplication().getApplicationContext(); twitter = new AsyncTwitterFactory().getInstance(); twitter.addListener(new TwitterListener()); twitter.setOAuthConsumer(getTwitterOauthKey(), getTwitterOauthSecret()); if (isSignedIn()) { twitter.setOAuthAccessToken(getAccessToken()); } loaded = true; } private SharedPreferences getSharedPreferences() {
return context.getSharedPreferences(Preferences.PREFERENCES_NAME, Context.MODE_PRIVATE);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
public void showUser(String screenName) { twitter.showUser(screenName); } public void retweetStatus(long statusId) { twitter.retweetStatus(statusId); } public void destroyStatus(long statusId) { twitter.destroyStatus(statusId); } public void createFavorite(long statusId) { twitter.createFavorite(statusId); } public void destroyFavorite(long statusId) { twitter.destroyFavorite(statusId); } public void updateStatus(StatusUpdate statusUpdate) { twitter.updateStatus(statusUpdate); } private class TwitterListener extends TwitterAdapter { @Override public void gotOAuthRequestToken(RequestToken token) { TwitterService.getInstance().setRequestToken(token);
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // } // Path: app/src/main/java/com/williammora/openfeed/services/TwitterService.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; public void showUser(String screenName) { twitter.showUser(screenName); } public void retweetStatus(long statusId) { twitter.retweetStatus(statusId); } public void destroyStatus(long statusId) { twitter.destroyStatus(statusId); } public void createFavorite(long statusId) { twitter.createFavorite(statusId); } public void destroyFavorite(long statusId) { twitter.destroyFavorite(statusId); } public void updateStatus(StatusUpdate statusUpdate) { twitter.updateStatus(statusUpdate); } private class TwitterListener extends TwitterAdapter { @Override public void gotOAuthRequestToken(RequestToken token) { TwitterService.getInstance().setRequestToken(token);
BusProvider.getInstance().post(new TwitterEvents.OAuthRequestTokenEvent(token), true);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
public void showUser(String screenName) { twitter.showUser(screenName); } public void retweetStatus(long statusId) { twitter.retweetStatus(statusId); } public void destroyStatus(long statusId) { twitter.destroyStatus(statusId); } public void createFavorite(long statusId) { twitter.createFavorite(statusId); } public void destroyFavorite(long statusId) { twitter.destroyFavorite(statusId); } public void updateStatus(StatusUpdate statusUpdate) { twitter.updateStatus(statusUpdate); } private class TwitterListener extends TwitterAdapter { @Override public void gotOAuthRequestToken(RequestToken token) { TwitterService.getInstance().setRequestToken(token);
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // } // Path: app/src/main/java/com/williammora/openfeed/services/TwitterService.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; public void showUser(String screenName) { twitter.showUser(screenName); } public void retweetStatus(long statusId) { twitter.retweetStatus(statusId); } public void destroyStatus(long statusId) { twitter.destroyStatus(statusId); } public void createFavorite(long statusId) { twitter.createFavorite(statusId); } public void destroyFavorite(long statusId) { twitter.destroyFavorite(statusId); } public void updateStatus(StatusUpdate statusUpdate) { twitter.updateStatus(statusUpdate); } private class TwitterListener extends TwitterAdapter { @Override public void gotOAuthRequestToken(RequestToken token) { TwitterService.getInstance().setRequestToken(token);
BusProvider.getInstance().post(new TwitterEvents.OAuthRequestTokenEvent(token), true);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/services/TwitterService.java
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken;
BusProvider.getInstance().post(new TwitterEvents.SearchEvent(queryResult), true); } @Override public void retweetedStatus(Status status) { BusProvider.getInstance().post(new TwitterEvents.RetweetedStatusEvent(status), true); } @Override public void createdFavorite(Status status) { BusProvider.getInstance().post(new TwitterEvents.CreatedFavoriteEvent(status), true); } @Override public void destroyedFavorite(Status status) { BusProvider.getInstance().post(new TwitterEvents.DestroyedFavoriteEvent(status), true); } @Override public void destroyedStatus(Status status) { BusProvider.getInstance().post(new TwitterEvents.DestroyedStatusEvent(status), true); } @Override public void gotUserDetail(User user) { BusProvider.getInstance().post(new TwitterEvents.UserEvent(user), true); } @Override public void updatedStatus(Status status) {
// Path: app/src/main/java/com/williammora/openfeed/OpenFeed.java // public class OpenFeed extends Application { // // private static OpenFeed application; // // public OpenFeed() { // application = this; // } // // public static OpenFeed getApplication() { // return application; // } // // @Override // public void onCreate() { // super.onCreate(); // TwitterService.getInstance().init(); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/NotificationEvent.java // public class NotificationEvent extends Event<String> { // // public NotificationEvent(String result) { // super(result); // } // } // // Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // // Path: app/src/main/java/com/williammora/openfeed/utils/BusProvider.java // public final class BusProvider { // private static OpenFeedBus BUS = new OpenFeedBus(); // // public static OpenFeedBus getInstance() { // return BUS; // } // // private BusProvider() { // } // } // // Path: app/src/main/java/com/williammora/openfeed/utils/Preferences.java // public class Preferences { // // public static final String PREFERENCES_NAME = "openfeed_preferences"; // public static final String TWITTER_ACCESS_TOKEN_KEY = "twitter_access_token_key"; // public static final String TWITTER_ACCESS_TOKEN_SECRET = "twitter_access_token_secret"; // // } // Path: app/src/main/java/com/williammora/openfeed/services/TwitterService.java import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import com.williammora.openfeed.BuildConfig; import com.williammora.openfeed.OpenFeed; import com.williammora.openfeed.R; import com.williammora.openfeed.events.NotificationEvent; import com.williammora.openfeed.events.TwitterEvents; import com.williammora.openfeed.utils.BusProvider; import com.williammora.openfeed.utils.Preferences; import twitter4j.AsyncTwitter; import twitter4j.AsyncTwitterFactory; import twitter4j.Paging; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; BusProvider.getInstance().post(new TwitterEvents.SearchEvent(queryResult), true); } @Override public void retweetedStatus(Status status) { BusProvider.getInstance().post(new TwitterEvents.RetweetedStatusEvent(status), true); } @Override public void createdFavorite(Status status) { BusProvider.getInstance().post(new TwitterEvents.CreatedFavoriteEvent(status), true); } @Override public void destroyedFavorite(Status status) { BusProvider.getInstance().post(new TwitterEvents.DestroyedFavoriteEvent(status), true); } @Override public void destroyedStatus(Status status) { BusProvider.getInstance().post(new TwitterEvents.DestroyedStatusEvent(status), true); } @Override public void gotUserDetail(User user) { BusProvider.getInstance().post(new TwitterEvents.UserEvent(user), true); } @Override public void updatedStatus(Status status) {
BusProvider.getInstance().post(new NotificationEvent("Status posted!"), true);
wmora/openfeed
app/src/main/java/com/williammora/openfeed/fragments/PopularSearchResultsFragment.java
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // }
import com.squareup.otto.Subscribe; import com.williammora.openfeed.events.TwitterEvents; import twitter4j.Query;
package com.williammora.openfeed.fragments; public class PopularSearchResultsFragment extends SearchResultsFragment { public static final String TAG = PopularSearchResultsFragment.class.getSimpleName(); @Override protected Query.ResultType getResultType() { return Query.ResultType.popular; } @Subscribe
// Path: app/src/main/java/com/williammora/openfeed/events/TwitterEvents.java // public class TwitterEvents { // // public static class OAuthRequestTokenEvent extends Event<RequestToken> { // public OAuthRequestTokenEvent(RequestToken result) { // super(result); // } // } // // public static class OAuthAccessTokenEvent extends Event<AccessToken> { // public OAuthAccessTokenEvent(AccessToken result) { // super(result); // } // } // // public static class HomeTimelineEvent extends Event<List<Status>> { // public HomeTimelineEvent(List<Status> result) { // super(result); // } // } // // public static class SearchEvent extends Event<QueryResult> { // public SearchEvent(QueryResult result) { // super(result); // } // } // // public static class UserEvent extends Event<User> { // public UserEvent(User result) { // super(result); // } // } // // public static class RetweetedStatusEvent extends Event<Status> { // public RetweetedStatusEvent(Status result) { // super(result); // } // } // // public static class CreatedFavoriteEvent extends Event<Status> { // public CreatedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedFavoriteEvent extends Event<Status> { // public DestroyedFavoriteEvent(Status result) { // super(result); // } // } // // public static class DestroyedStatusEvent extends Event<Status> { // public DestroyedStatusEvent(Status result) { // super(result); // } // } // // } // Path: app/src/main/java/com/williammora/openfeed/fragments/PopularSearchResultsFragment.java import com.squareup.otto.Subscribe; import com.williammora.openfeed.events.TwitterEvents; import twitter4j.Query; package com.williammora.openfeed.fragments; public class PopularSearchResultsFragment extends SearchResultsFragment { public static final String TAG = PopularSearchResultsFragment.class.getSimpleName(); @Override protected Query.ResultType getResultType() { return Query.ResultType.popular; } @Subscribe
public void onSearchEvent(TwitterEvents.SearchEvent event) {
wmora/openfeed
app/src/main/java/com/williammora/openfeed/listeners/OnUserClickListener.java
// Path: app/src/main/java/com/williammora/openfeed/activities/UserActivity.java // public class UserActivity extends OpenFeedActivity implements UserFragment.UserFragmentListener { // // public static final String EXTRA_USER = "EXTRA_USER"; // public static final String SAVED_USER = "SAVED_USER"; // public static final String SAVED_SCREEN_NAME = "SAVED_SCREEN_NAME"; // // private User mUser; // private String mScreenName; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_user); // if (savedInstanceState == null) { // getFragmentManager().beginTransaction() // .add(R.id.container, new UserFragment()) // .commit(); // Intent intent = getIntent(); // mUser = (User) intent.getSerializableExtra(EXTRA_USER); // if (mUser == null) { // Uri uri = getIntent().getData(); // if (uri.getHost().equals(getString(R.string.twitter_users_host))) { // mScreenName = uri.getLastPathSegment(); // } // } // } // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_USER, mUser); // outState.putString(SAVED_SCREEN_NAME, mScreenName); // super.onSaveInstanceState(outState); // } // // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); // mUser = (User) savedInstanceState.getSerializable(SAVED_USER); // mScreenName = savedInstanceState.getString(SAVED_SCREEN_NAME, ""); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // switch (item.getItemId()) { // case android.R.id.home: // finish(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public User getUser() { // return mUser; // } // // @Override // public String getUserScreenName() { // return mScreenName; // } // // @Subscribe // public void onUserEvent(TwitterEvents.UserEvent event) { // User user = event.getResult(); // setTitle(user.getName()); // mUser = user; // } // }
import android.content.Intent; import android.view.View; import com.williammora.openfeed.activities.UserActivity; import twitter4j.User;
package com.williammora.openfeed.listeners; public class OnUserClickListener implements View.OnClickListener { private User mUser; public OnUserClickListener(User user) { mUser = user; } @Override public void onClick(View view) { Intent intent = new Intent();
// Path: app/src/main/java/com/williammora/openfeed/activities/UserActivity.java // public class UserActivity extends OpenFeedActivity implements UserFragment.UserFragmentListener { // // public static final String EXTRA_USER = "EXTRA_USER"; // public static final String SAVED_USER = "SAVED_USER"; // public static final String SAVED_SCREEN_NAME = "SAVED_SCREEN_NAME"; // // private User mUser; // private String mScreenName; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_user); // if (savedInstanceState == null) { // getFragmentManager().beginTransaction() // .add(R.id.container, new UserFragment()) // .commit(); // Intent intent = getIntent(); // mUser = (User) intent.getSerializableExtra(EXTRA_USER); // if (mUser == null) { // Uri uri = getIntent().getData(); // if (uri.getHost().equals(getString(R.string.twitter_users_host))) { // mScreenName = uri.getLastPathSegment(); // } // } // } // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // outState.putSerializable(SAVED_USER, mUser); // outState.putString(SAVED_SCREEN_NAME, mScreenName); // super.onSaveInstanceState(outState); // } // // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); // mUser = (User) savedInstanceState.getSerializable(SAVED_USER); // mScreenName = savedInstanceState.getString(SAVED_SCREEN_NAME, ""); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // switch (item.getItemId()) { // case android.R.id.home: // finish(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public User getUser() { // return mUser; // } // // @Override // public String getUserScreenName() { // return mScreenName; // } // // @Subscribe // public void onUserEvent(TwitterEvents.UserEvent event) { // User user = event.getResult(); // setTitle(user.getName()); // mUser = user; // } // } // Path: app/src/main/java/com/williammora/openfeed/listeners/OnUserClickListener.java import android.content.Intent; import android.view.View; import com.williammora.openfeed.activities.UserActivity; import twitter4j.User; package com.williammora.openfeed.listeners; public class OnUserClickListener implements View.OnClickListener { private User mUser; public OnUserClickListener(User user) { mUser = user; } @Override public void onClick(View view) { Intent intent = new Intent();
intent.setClass(view.getContext(), UserActivity.class);
tarun3kumar/seleniumtestsframework
src/test/java/com/seleniumtests/tests/JSErrorTest.java
// Path: src/test/java/com/seleniumtests/webpage/JSErrorPage.java // public class JSErrorPage extends PageObject { // // public JSErrorPage(final boolean openPageURL) throws Exception { // super(null, openPageURL ? SeleniumTestsContextManager.getThreadContext().getAppURL() : // null); // } // }
import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.webpage.JSErrorPage; import org.testng.annotations.Test;
/* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; public class JSErrorTest extends SeleniumTestPlan { @Test(groups = {"jsErrorTest"}, description = "jsErrorTest") public void jsErrorTest() throws Exception {
// Path: src/test/java/com/seleniumtests/webpage/JSErrorPage.java // public class JSErrorPage extends PageObject { // // public JSErrorPage(final boolean openPageURL) throws Exception { // super(null, openPageURL ? SeleniumTestsContextManager.getThreadContext().getAppURL() : // null); // } // } // Path: src/test/java/com/seleniumtests/tests/JSErrorTest.java import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.webpage.JSErrorPage; import org.testng.annotations.Test; /* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; public class JSErrorTest extends SeleniumTestPlan { @Test(groups = {"jsErrorTest"}, description = "jsErrorTest") public void jsErrorTest() throws Exception {
new JSErrorPage(true);
tarun3kumar/seleniumtestsframework
src/test/java/com/seleniumtests/tests/RegistrationTest.java
// Path: src/main/java/com/seleniumtests/core/CustomAssertion.java // public static void assertThat(final String reason, final boolean assertion) { // if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { // softAssertThat(reason, assertion); // } else { // MatcherAssert.assertThat(reason, assertion); // } // } // // Path: src/test/java/com/seleniumtests/webpage/LoginPage.java // public class LoginPage extends PageObject { // // private static final TextFieldElement userNameTextBox = new TextFieldElement("Username Textbox", // locateByName("usernameLoginPage")); // // private static final TextFieldElement passwordTextBox = new TextFieldElement("Password Textbox", // locateByName("psw1")); // // private ButtonElement submitButton = new ButtonElement("submit Button", // locateByCSSSelector("input~input[value='Submit']")); // // public LoginPage() throws Exception { // super(userNameTextBox); // } // // public LoginPage enterUserName(final String userName) { // userNameTextBox.clearAndType(userName); // // return this; // } // // public LoginPage enterPassword(final String password) { // userNameTextBox.clearAndType(password); // // return this; // } // // public static boolean isUserNameDisplayed() { // return userNameTextBox.isDisplayed(); // } // // /** // * Google Home Page is not part of seleniumtests.com but this how you can move from one page object to another. // * // * @return // * // * @throws Exception // */ // public GoogleHomePage clickSubmitButton() throws Exception { // submitButton.click(); // // return new GoogleHomePage(); // } // // public GoogleHomePage enterLoginData(final User user) throws Exception { // return enterUserName(user.getUserName()).enterPassword(user.getPassword()).clickSubmitButton(); // } // } // // Path: src/test/java/com/seleniumtests/webpage/RegistrationPage.java // public class RegistrationPage extends PageObject { // // // // https://github.com/appium/appium/issues/13306 > w3c standard only declares css and xpath locators // private static final TextFieldElement firstNameTextbox = new TextFieldElement("First name text box", // locateByCSSSelector("input[name='firstname']")); // // private TextFieldElement lastNameTextbox = new TextFieldElement("Last name text box", locateByName("lastname")); // // private TextFieldElement userNameTextbox = new TextFieldElement("user name text box", locateByName("username")); // // private TextFieldElement pwd1NameTextbox = new TextFieldElement("password 1 text box", locateByName("psw1")); // // private TextFieldElement pwd2NameTextbox = new TextFieldElement("password 2 text box", locateByName("psw2")); // // private ButtonElement submitButton = new ButtonElement("submit Button", // locateByCSSSelector("input~input[value='Submit']")); // // public RegistrationPage(final boolean openPageURL) throws Exception { // super(firstNameTextbox, openPageURL ? SeleniumTestsContextManager.getThreadContext().getAppURL() : null); // } // // public RegistrationPage enterFirstName(final String firstName) { // firstNameTextbox.clearAndType(firstName); // // return this; // } // // public RegistrationPage enterLastName(final String lastName) { // lastNameTextbox.clearAndType(lastName); // // return this; // } // // public RegistrationPage enterUserName(final String userName) { // userNameTextbox.clearAndType(userName); // // return this; // } // // public RegistrationPage enterPassword(final String password) { // pwd1NameTextbox.clearAndType(password); // // return this; // } // // public RegistrationPage enterConfirmPassword(final String password) { // pwd2NameTextbox.clearAndType(password); // // return this; // } // // public LoginPage clickSubmitButton() throws Exception { // submitButton.click(); // // return new LoginPage(); // } // // public LoginPage submitValidRegistrationData(final User user) throws Exception { // return enterFirstName(user.getFirstName()).enterLastName(user.getLastName()).enterUserName(user.getUserName()) // .enterPassword(user.getPassword()) // .enterConfirmPassword(user.getPassword()).clickSubmitButton(); // } // // }
import com.seleniumtests.webpage.RegistrationPage; import static com.seleniumtests.core.CustomAssertion.assertThat; import static org.hamcrest.CoreMatchers.is; import java.lang.reflect.Method; import java.util.Iterator; import java.util.LinkedHashMap; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.seleniumtests.core.Filter; import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.dataobject.User; import com.seleniumtests.util.SpreadSheetHelper; import com.seleniumtests.util.internal.entity.TestEntity; import com.seleniumtests.webpage.GoogleHomePage; import com.seleniumtests.webpage.LoginPage;
/* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; public class RegistrationTest extends SeleniumTestPlan { @DataProvider( name = "loginData", parallel = true ) public static Iterator<Object[]> getUserInfo(final Method m) throws Exception { Filter filter = Filter.equalsIgnoreCase(TestEntity.TEST_METHOD, m.getName()); LinkedHashMap<String, Class<?>> classMap = new LinkedHashMap<String, Class<?>>(); classMap.put("TestEntity", TestEntity.class); classMap.put("User", User.class); return SpreadSheetHelper.getEntitiesFromSpreadsheet( RegistrationTest.class, classMap, "loginuser.csv", filter); } @Test( groups = { "registerWithValidUserData" }, dataProvider = "loginData", description = "Register with valid login data" ) public void registerWithValidUserData(final TestEntity testEntity, final User user) throws Exception {
// Path: src/main/java/com/seleniumtests/core/CustomAssertion.java // public static void assertThat(final String reason, final boolean assertion) { // if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { // softAssertThat(reason, assertion); // } else { // MatcherAssert.assertThat(reason, assertion); // } // } // // Path: src/test/java/com/seleniumtests/webpage/LoginPage.java // public class LoginPage extends PageObject { // // private static final TextFieldElement userNameTextBox = new TextFieldElement("Username Textbox", // locateByName("usernameLoginPage")); // // private static final TextFieldElement passwordTextBox = new TextFieldElement("Password Textbox", // locateByName("psw1")); // // private ButtonElement submitButton = new ButtonElement("submit Button", // locateByCSSSelector("input~input[value='Submit']")); // // public LoginPage() throws Exception { // super(userNameTextBox); // } // // public LoginPage enterUserName(final String userName) { // userNameTextBox.clearAndType(userName); // // return this; // } // // public LoginPage enterPassword(final String password) { // userNameTextBox.clearAndType(password); // // return this; // } // // public static boolean isUserNameDisplayed() { // return userNameTextBox.isDisplayed(); // } // // /** // * Google Home Page is not part of seleniumtests.com but this how you can move from one page object to another. // * // * @return // * // * @throws Exception // */ // public GoogleHomePage clickSubmitButton() throws Exception { // submitButton.click(); // // return new GoogleHomePage(); // } // // public GoogleHomePage enterLoginData(final User user) throws Exception { // return enterUserName(user.getUserName()).enterPassword(user.getPassword()).clickSubmitButton(); // } // } // // Path: src/test/java/com/seleniumtests/webpage/RegistrationPage.java // public class RegistrationPage extends PageObject { // // // // https://github.com/appium/appium/issues/13306 > w3c standard only declares css and xpath locators // private static final TextFieldElement firstNameTextbox = new TextFieldElement("First name text box", // locateByCSSSelector("input[name='firstname']")); // // private TextFieldElement lastNameTextbox = new TextFieldElement("Last name text box", locateByName("lastname")); // // private TextFieldElement userNameTextbox = new TextFieldElement("user name text box", locateByName("username")); // // private TextFieldElement pwd1NameTextbox = new TextFieldElement("password 1 text box", locateByName("psw1")); // // private TextFieldElement pwd2NameTextbox = new TextFieldElement("password 2 text box", locateByName("psw2")); // // private ButtonElement submitButton = new ButtonElement("submit Button", // locateByCSSSelector("input~input[value='Submit']")); // // public RegistrationPage(final boolean openPageURL) throws Exception { // super(firstNameTextbox, openPageURL ? SeleniumTestsContextManager.getThreadContext().getAppURL() : null); // } // // public RegistrationPage enterFirstName(final String firstName) { // firstNameTextbox.clearAndType(firstName); // // return this; // } // // public RegistrationPage enterLastName(final String lastName) { // lastNameTextbox.clearAndType(lastName); // // return this; // } // // public RegistrationPage enterUserName(final String userName) { // userNameTextbox.clearAndType(userName); // // return this; // } // // public RegistrationPage enterPassword(final String password) { // pwd1NameTextbox.clearAndType(password); // // return this; // } // // public RegistrationPage enterConfirmPassword(final String password) { // pwd2NameTextbox.clearAndType(password); // // return this; // } // // public LoginPage clickSubmitButton() throws Exception { // submitButton.click(); // // return new LoginPage(); // } // // public LoginPage submitValidRegistrationData(final User user) throws Exception { // return enterFirstName(user.getFirstName()).enterLastName(user.getLastName()).enterUserName(user.getUserName()) // .enterPassword(user.getPassword()) // .enterConfirmPassword(user.getPassword()).clickSubmitButton(); // } // // } // Path: src/test/java/com/seleniumtests/tests/RegistrationTest.java import com.seleniumtests.webpage.RegistrationPage; import static com.seleniumtests.core.CustomAssertion.assertThat; import static org.hamcrest.CoreMatchers.is; import java.lang.reflect.Method; import java.util.Iterator; import java.util.LinkedHashMap; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.seleniumtests.core.Filter; import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.dataobject.User; import com.seleniumtests.util.SpreadSheetHelper; import com.seleniumtests.util.internal.entity.TestEntity; import com.seleniumtests.webpage.GoogleHomePage; import com.seleniumtests.webpage.LoginPage; /* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; public class RegistrationTest extends SeleniumTestPlan { @DataProvider( name = "loginData", parallel = true ) public static Iterator<Object[]> getUserInfo(final Method m) throws Exception { Filter filter = Filter.equalsIgnoreCase(TestEntity.TEST_METHOD, m.getName()); LinkedHashMap<String, Class<?>> classMap = new LinkedHashMap<String, Class<?>>(); classMap.put("TestEntity", TestEntity.class); classMap.put("User", User.class); return SpreadSheetHelper.getEntitiesFromSpreadsheet( RegistrationTest.class, classMap, "loginuser.csv", filter); } @Test( groups = { "registerWithValidUserData" }, dataProvider = "loginData", description = "Register with valid login data" ) public void registerWithValidUserData(final TestEntity testEntity, final User user) throws Exception {
new RegistrationPage(true).submitValidRegistrationData(user);
tarun3kumar/seleniumtestsframework
src/main/java/com/seleniumtests/webelements/CheckBoxElement.java
// Path: src/main/java/com/seleniumtests/core/TestLogging.java // public class TestLogging { // // private static Map<String, Map<String, Map<String, List<String>>>> logMap = Collections.synchronizedMap( // new HashMap<String, Map<String, Map<String, List<String>>>>()); // // /** // * error Logger. // * // * @param message // */ // public static void errorLogger(String message) { // message = "<li><b><font color='#6600CC'>" + message + "</font></b></li>"; // log(message, false, false); // } // // public static Logger getLogger(final Class<?> cls) { // boolean rootIsConfigured = Logger.getRootLogger().getAllAppenders().hasMoreElements(); // if (!rootIsConfigured) { // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(Level.INFO); // // Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement(); // appender.setLayout(new PatternLayout(" %-5p %d [%t] %C{1}: %m%n")); // } // // return Logger.getLogger(cls); // } // // public static Map<String, Map<String, List<String>>> getPageListenerLog(final String pageListenerClassName) { // return logMap.get(pageListenerClassName); // } // // public static List<String> getPageListenerLogByMethodInstance(final ITestResult testResult) { // // for (Entry<String, Map<String, Map<String, List<String>>>> listenerEntry : logMap.entrySet()) { // if (!PluginsHelper.getInstance().isTestResultEffected(listenerEntry.getKey())) { // continue; // } // // Map<String, Map<String, List<String>>> pageMap = listenerEntry.getValue(); // for (Entry<String, Map<String, List<String>>> pageEntry : pageMap.entrySet()) { // Map<String, List<String>> errorMap = pageEntry.getValue(); // String methodInstance = StringUtility.constructMethodSignature(testResult.getMethod() // .getConstructorOrMethod().getMethod(), testResult.getParameters()); // return errorMap.get(methodInstance); // } // } // // return null; // } // // /** // * Log info. // * // * @param message // */ // public static void logInfo(String message) { // message = "<li><font color='#00cd00'>" + message + "</font></li>"; // log(message, false, false); // } // // /** // * Log method. // * // * @param message // */ // public static void log(final String message) { // log(message, false, false); // } // // /** // * Log. // * // * @param message // * @param logToStandardOutput // */ // public static void log(final String message, final boolean logToStandardOutput) { // log(message, false, logToStandardOutput); // } // // public static void log(String message, final boolean failed, final boolean logToStandardOutput) { // // if (message == null) { // message = ""; // } // // message = message.replaceAll("\\n", "<br/>"); // // if (failed) { // message = "<span style=\"font-weight:bold;color:#cc0052;\">" + message + "</span>"; // } // // Reporter.log(escape(message), logToStandardOutput); // } // // public static String escape(final String message) { // return message.replaceAll("\\n", "<br/>").replaceAll("<", "@@lt@@").replaceAll(">", "^^greaterThan^^"); // } // // public static String unEscape(String message) { // message = message.replaceAll("<br/>", "\\n").replaceAll("@@lt@@", "<").replaceAll("\\^\\^gt\\^\\^", ">"); // // message = HtmlToText.htmlToPlainText(message); // return message; // } // // public static void logWebOutput(final String url, final String message, final boolean failed) { // log("Output: " + message + "<br/>", failed, false); // } // // public static void logWebStep(final String message, final boolean failed) { // log("<li>" + (failed ? "<b>FailedStep</b>: " : " ") + message + "</li>", failed, false); // } // // public static String buildScreenshotLog(final ScreenShot screenShot) { // StringBuffer sbMessage = new StringBuffer(); // if (screenShot.getLocation() != null) { // sbMessage.append("<a href='" + screenShot.getLocation() + "' target=url>Application URL</a>"); // } // // if (screenShot.getHtmlSourcePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getHtmlSourcePath() // + "' target=html>Application HTML Source</a>"); // } // // if (screenShot.getImagePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getImagePath() // + "' class='lightbox'>Application Snapshot</a>"); // } // // return sbMessage.toString(); // } // // /** // * Log method. // * // * @param message // */ // public static void warning(String message) { // message = "<li><font color='#FFFF00'>" + message + "</font></li>"; // log(message, false, false); // } // }
import com.seleniumtests.core.TestLogging; import org.openqa.selenium.By;
/* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.webelements; public class CheckBoxElement extends HtmlElement { public CheckBoxElement(final String label, final By by) { super(label, by); } @Override public void check() {
// Path: src/main/java/com/seleniumtests/core/TestLogging.java // public class TestLogging { // // private static Map<String, Map<String, Map<String, List<String>>>> logMap = Collections.synchronizedMap( // new HashMap<String, Map<String, Map<String, List<String>>>>()); // // /** // * error Logger. // * // * @param message // */ // public static void errorLogger(String message) { // message = "<li><b><font color='#6600CC'>" + message + "</font></b></li>"; // log(message, false, false); // } // // public static Logger getLogger(final Class<?> cls) { // boolean rootIsConfigured = Logger.getRootLogger().getAllAppenders().hasMoreElements(); // if (!rootIsConfigured) { // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(Level.INFO); // // Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement(); // appender.setLayout(new PatternLayout(" %-5p %d [%t] %C{1}: %m%n")); // } // // return Logger.getLogger(cls); // } // // public static Map<String, Map<String, List<String>>> getPageListenerLog(final String pageListenerClassName) { // return logMap.get(pageListenerClassName); // } // // public static List<String> getPageListenerLogByMethodInstance(final ITestResult testResult) { // // for (Entry<String, Map<String, Map<String, List<String>>>> listenerEntry : logMap.entrySet()) { // if (!PluginsHelper.getInstance().isTestResultEffected(listenerEntry.getKey())) { // continue; // } // // Map<String, Map<String, List<String>>> pageMap = listenerEntry.getValue(); // for (Entry<String, Map<String, List<String>>> pageEntry : pageMap.entrySet()) { // Map<String, List<String>> errorMap = pageEntry.getValue(); // String methodInstance = StringUtility.constructMethodSignature(testResult.getMethod() // .getConstructorOrMethod().getMethod(), testResult.getParameters()); // return errorMap.get(methodInstance); // } // } // // return null; // } // // /** // * Log info. // * // * @param message // */ // public static void logInfo(String message) { // message = "<li><font color='#00cd00'>" + message + "</font></li>"; // log(message, false, false); // } // // /** // * Log method. // * // * @param message // */ // public static void log(final String message) { // log(message, false, false); // } // // /** // * Log. // * // * @param message // * @param logToStandardOutput // */ // public static void log(final String message, final boolean logToStandardOutput) { // log(message, false, logToStandardOutput); // } // // public static void log(String message, final boolean failed, final boolean logToStandardOutput) { // // if (message == null) { // message = ""; // } // // message = message.replaceAll("\\n", "<br/>"); // // if (failed) { // message = "<span style=\"font-weight:bold;color:#cc0052;\">" + message + "</span>"; // } // // Reporter.log(escape(message), logToStandardOutput); // } // // public static String escape(final String message) { // return message.replaceAll("\\n", "<br/>").replaceAll("<", "@@lt@@").replaceAll(">", "^^greaterThan^^"); // } // // public static String unEscape(String message) { // message = message.replaceAll("<br/>", "\\n").replaceAll("@@lt@@", "<").replaceAll("\\^\\^gt\\^\\^", ">"); // // message = HtmlToText.htmlToPlainText(message); // return message; // } // // public static void logWebOutput(final String url, final String message, final boolean failed) { // log("Output: " + message + "<br/>", failed, false); // } // // public static void logWebStep(final String message, final boolean failed) { // log("<li>" + (failed ? "<b>FailedStep</b>: " : " ") + message + "</li>", failed, false); // } // // public static String buildScreenshotLog(final ScreenShot screenShot) { // StringBuffer sbMessage = new StringBuffer(); // if (screenShot.getLocation() != null) { // sbMessage.append("<a href='" + screenShot.getLocation() + "' target=url>Application URL</a>"); // } // // if (screenShot.getHtmlSourcePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getHtmlSourcePath() // + "' target=html>Application HTML Source</a>"); // } // // if (screenShot.getImagePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getImagePath() // + "' class='lightbox'>Application Snapshot</a>"); // } // // return sbMessage.toString(); // } // // /** // * Log method. // * // * @param message // */ // public static void warning(String message) { // message = "<li><font color='#FFFF00'>" + message + "</font></li>"; // log(message, false, false); // } // } // Path: src/main/java/com/seleniumtests/webelements/CheckBoxElement.java import com.seleniumtests.core.TestLogging; import org.openqa.selenium.By; /* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.webelements; public class CheckBoxElement extends HtmlElement { public CheckBoxElement(final String label, final By by) { super(label, by); } @Override public void check() {
TestLogging.logWebStep("check " + toHTML(), false);
tarun3kumar/seleniumtestsframework
src/main/java/com/seleniumtests/reporter/PluginsHelper.java
// Path: src/main/java/com/seleniumtests/reporter/pluginmodel/Page.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "") // @XmlRootElement(name = "page") // public class Page { // // @XmlAttribute(name = "class-name", required = true) // protected String className; // // /** // * Gets the value of the className property. // * // * @return possible object is {@link String } // */ // public String getClassName() { // return className; // } // // /** // * Sets the value of the className property. // * // * @param value allowed object is {@link String } // */ // public void setClassName(final String value) { // this.className = value; // } // // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import com.seleniumtests.core.SeleniumTestsPageListener; import com.seleniumtests.reporter.pluginmodel.Method; import com.seleniumtests.reporter.pluginmodel.Page; import com.seleniumtests.reporter.pluginmodel.Plugin; import com.seleniumtests.reporter.pluginmodel.SeleniumTestsPlugins; import com.seleniumtests.reporter.pluginmodel.Test; import com.seleniumtests.webelements.IPage;
List<SeleniumTestsPageListener> pageListenerList = new ArrayList<SeleniumTestsPageListener>(); for (Plugin plugin : _seleniumTestsPlugins.getPlugin()) { if (isPageListenerApplicable(plugin, testMethodSignature, page.getClass().getCanonicalName())) { pageListenerList.add(pageListenerMap.get(plugin.getClassName().trim())); } } for (SeleniumTestsPageListener listener : pageListenerList) { try { if (isPageLoad) { listener.onPageLoad(page); } else { listener.onPageUnload(page); } } catch (Throwable e) { logger.error(e); } } } public boolean isPageListenerApplicable(final Plugin plugin, final String testMethodSignature, final String pageClassName) { if (testMethodSignature == null) { return true; } boolean testFound = false; for (Test test : plugin.getTest()) { if (testMethodSignature.matches(test.getClassName() + "\\.\\w.*")) {
// Path: src/main/java/com/seleniumtests/reporter/pluginmodel/Page.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "") // @XmlRootElement(name = "page") // public class Page { // // @XmlAttribute(name = "class-name", required = true) // protected String className; // // /** // * Gets the value of the className property. // * // * @return possible object is {@link String } // */ // public String getClassName() { // return className; // } // // /** // * Sets the value of the className property. // * // * @param value allowed object is {@link String } // */ // public void setClassName(final String value) { // this.className = value; // } // // } // Path: src/main/java/com/seleniumtests/reporter/PluginsHelper.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.log4j.Logger; import com.seleniumtests.core.SeleniumTestsPageListener; import com.seleniumtests.reporter.pluginmodel.Method; import com.seleniumtests.reporter.pluginmodel.Page; import com.seleniumtests.reporter.pluginmodel.Plugin; import com.seleniumtests.reporter.pluginmodel.SeleniumTestsPlugins; import com.seleniumtests.reporter.pluginmodel.Test; import com.seleniumtests.webelements.IPage; List<SeleniumTestsPageListener> pageListenerList = new ArrayList<SeleniumTestsPageListener>(); for (Plugin plugin : _seleniumTestsPlugins.getPlugin()) { if (isPageListenerApplicable(plugin, testMethodSignature, page.getClass().getCanonicalName())) { pageListenerList.add(pageListenerMap.get(plugin.getClassName().trim())); } } for (SeleniumTestsPageListener listener : pageListenerList) { try { if (isPageLoad) { listener.onPageLoad(page); } else { listener.onPageUnload(page); } } catch (Throwable e) { logger.error(e); } } } public boolean isPageListenerApplicable(final Plugin plugin, final String testMethodSignature, final String pageClassName) { if (testMethodSignature == null) { return true; } boolean testFound = false; for (Test test : plugin.getTest()) { if (testMethodSignature.matches(test.getClassName() + "\\.\\w.*")) {
for (Page page : test.getPage()) {
tarun3kumar/seleniumtestsframework
src/main/java/com/seleniumtests/webelements/RadioButtonElement.java
// Path: src/main/java/com/seleniumtests/core/TestLogging.java // public class TestLogging { // // private static Map<String, Map<String, Map<String, List<String>>>> logMap = Collections.synchronizedMap( // new HashMap<String, Map<String, Map<String, List<String>>>>()); // // /** // * error Logger. // * // * @param message // */ // public static void errorLogger(String message) { // message = "<li><b><font color='#6600CC'>" + message + "</font></b></li>"; // log(message, false, false); // } // // public static Logger getLogger(final Class<?> cls) { // boolean rootIsConfigured = Logger.getRootLogger().getAllAppenders().hasMoreElements(); // if (!rootIsConfigured) { // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(Level.INFO); // // Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement(); // appender.setLayout(new PatternLayout(" %-5p %d [%t] %C{1}: %m%n")); // } // // return Logger.getLogger(cls); // } // // public static Map<String, Map<String, List<String>>> getPageListenerLog(final String pageListenerClassName) { // return logMap.get(pageListenerClassName); // } // // public static List<String> getPageListenerLogByMethodInstance(final ITestResult testResult) { // // for (Entry<String, Map<String, Map<String, List<String>>>> listenerEntry : logMap.entrySet()) { // if (!PluginsHelper.getInstance().isTestResultEffected(listenerEntry.getKey())) { // continue; // } // // Map<String, Map<String, List<String>>> pageMap = listenerEntry.getValue(); // for (Entry<String, Map<String, List<String>>> pageEntry : pageMap.entrySet()) { // Map<String, List<String>> errorMap = pageEntry.getValue(); // String methodInstance = StringUtility.constructMethodSignature(testResult.getMethod() // .getConstructorOrMethod().getMethod(), testResult.getParameters()); // return errorMap.get(methodInstance); // } // } // // return null; // } // // /** // * Log info. // * // * @param message // */ // public static void logInfo(String message) { // message = "<li><font color='#00cd00'>" + message + "</font></li>"; // log(message, false, false); // } // // /** // * Log method. // * // * @param message // */ // public static void log(final String message) { // log(message, false, false); // } // // /** // * Log. // * // * @param message // * @param logToStandardOutput // */ // public static void log(final String message, final boolean logToStandardOutput) { // log(message, false, logToStandardOutput); // } // // public static void log(String message, final boolean failed, final boolean logToStandardOutput) { // // if (message == null) { // message = ""; // } // // message = message.replaceAll("\\n", "<br/>"); // // if (failed) { // message = "<span style=\"font-weight:bold;color:#cc0052;\">" + message + "</span>"; // } // // Reporter.log(escape(message), logToStandardOutput); // } // // public static String escape(final String message) { // return message.replaceAll("\\n", "<br/>").replaceAll("<", "@@lt@@").replaceAll(">", "^^greaterThan^^"); // } // // public static String unEscape(String message) { // message = message.replaceAll("<br/>", "\\n").replaceAll("@@lt@@", "<").replaceAll("\\^\\^gt\\^\\^", ">"); // // message = HtmlToText.htmlToPlainText(message); // return message; // } // // public static void logWebOutput(final String url, final String message, final boolean failed) { // log("Output: " + message + "<br/>", failed, false); // } // // public static void logWebStep(final String message, final boolean failed) { // log("<li>" + (failed ? "<b>FailedStep</b>: " : " ") + message + "</li>", failed, false); // } // // public static String buildScreenshotLog(final ScreenShot screenShot) { // StringBuffer sbMessage = new StringBuffer(); // if (screenShot.getLocation() != null) { // sbMessage.append("<a href='" + screenShot.getLocation() + "' target=url>Application URL</a>"); // } // // if (screenShot.getHtmlSourcePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getHtmlSourcePath() // + "' target=html>Application HTML Source</a>"); // } // // if (screenShot.getImagePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getImagePath() // + "' class='lightbox'>Application Snapshot</a>"); // } // // return sbMessage.toString(); // } // // /** // * Log method. // * // * @param message // */ // public static void warning(String message) { // message = "<li><font color='#FFFF00'>" + message + "</font></li>"; // log(message, false, false); // } // }
import com.seleniumtests.core.TestLogging; import org.openqa.selenium.By;
/* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.webelements; public class RadioButtonElement extends HtmlElement { public RadioButtonElement(final String label, final By by) { super(label, by); } @Override public void check() {
// Path: src/main/java/com/seleniumtests/core/TestLogging.java // public class TestLogging { // // private static Map<String, Map<String, Map<String, List<String>>>> logMap = Collections.synchronizedMap( // new HashMap<String, Map<String, Map<String, List<String>>>>()); // // /** // * error Logger. // * // * @param message // */ // public static void errorLogger(String message) { // message = "<li><b><font color='#6600CC'>" + message + "</font></b></li>"; // log(message, false, false); // } // // public static Logger getLogger(final Class<?> cls) { // boolean rootIsConfigured = Logger.getRootLogger().getAllAppenders().hasMoreElements(); // if (!rootIsConfigured) { // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(Level.INFO); // // Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement(); // appender.setLayout(new PatternLayout(" %-5p %d [%t] %C{1}: %m%n")); // } // // return Logger.getLogger(cls); // } // // public static Map<String, Map<String, List<String>>> getPageListenerLog(final String pageListenerClassName) { // return logMap.get(pageListenerClassName); // } // // public static List<String> getPageListenerLogByMethodInstance(final ITestResult testResult) { // // for (Entry<String, Map<String, Map<String, List<String>>>> listenerEntry : logMap.entrySet()) { // if (!PluginsHelper.getInstance().isTestResultEffected(listenerEntry.getKey())) { // continue; // } // // Map<String, Map<String, List<String>>> pageMap = listenerEntry.getValue(); // for (Entry<String, Map<String, List<String>>> pageEntry : pageMap.entrySet()) { // Map<String, List<String>> errorMap = pageEntry.getValue(); // String methodInstance = StringUtility.constructMethodSignature(testResult.getMethod() // .getConstructorOrMethod().getMethod(), testResult.getParameters()); // return errorMap.get(methodInstance); // } // } // // return null; // } // // /** // * Log info. // * // * @param message // */ // public static void logInfo(String message) { // message = "<li><font color='#00cd00'>" + message + "</font></li>"; // log(message, false, false); // } // // /** // * Log method. // * // * @param message // */ // public static void log(final String message) { // log(message, false, false); // } // // /** // * Log. // * // * @param message // * @param logToStandardOutput // */ // public static void log(final String message, final boolean logToStandardOutput) { // log(message, false, logToStandardOutput); // } // // public static void log(String message, final boolean failed, final boolean logToStandardOutput) { // // if (message == null) { // message = ""; // } // // message = message.replaceAll("\\n", "<br/>"); // // if (failed) { // message = "<span style=\"font-weight:bold;color:#cc0052;\">" + message + "</span>"; // } // // Reporter.log(escape(message), logToStandardOutput); // } // // public static String escape(final String message) { // return message.replaceAll("\\n", "<br/>").replaceAll("<", "@@lt@@").replaceAll(">", "^^greaterThan^^"); // } // // public static String unEscape(String message) { // message = message.replaceAll("<br/>", "\\n").replaceAll("@@lt@@", "<").replaceAll("\\^\\^gt\\^\\^", ">"); // // message = HtmlToText.htmlToPlainText(message); // return message; // } // // public static void logWebOutput(final String url, final String message, final boolean failed) { // log("Output: " + message + "<br/>", failed, false); // } // // public static void logWebStep(final String message, final boolean failed) { // log("<li>" + (failed ? "<b>FailedStep</b>: " : " ") + message + "</li>", failed, false); // } // // public static String buildScreenshotLog(final ScreenShot screenShot) { // StringBuffer sbMessage = new StringBuffer(); // if (screenShot.getLocation() != null) { // sbMessage.append("<a href='" + screenShot.getLocation() + "' target=url>Application URL</a>"); // } // // if (screenShot.getHtmlSourcePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getHtmlSourcePath() // + "' target=html>Application HTML Source</a>"); // } // // if (screenShot.getImagePath() != null) { // sbMessage.append(" | <a href='" + screenShot.getImagePath() // + "' class='lightbox'>Application Snapshot</a>"); // } // // return sbMessage.toString(); // } // // /** // * Log method. // * // * @param message // */ // public static void warning(String message) { // message = "<li><font color='#FFFF00'>" + message + "</font></li>"; // log(message, false, false); // } // } // Path: src/main/java/com/seleniumtests/webelements/RadioButtonElement.java import com.seleniumtests.core.TestLogging; import org.openqa.selenium.By; /* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.webelements; public class RadioButtonElement extends HtmlElement { public RadioButtonElement(final String label, final By by) { super(label, by); } @Override public void check() {
TestLogging.logWebStep("check " + toHTML(), false);
tarun3kumar/seleniumtestsframework
src/test/java/com/seleniumtests/tests/IOSAppTest.java
// Path: src/main/java/com/seleniumtests/core/CustomAssertion.java // public static void assertThat(final String reason, final boolean assertion) { // if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { // softAssertThat(reason, assertion); // } else { // MatcherAssert.assertThat(reason, assertion); // } // }
import static com.seleniumtests.core.CustomAssertion.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import org.testng.annotations.Test; import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.webpage.UICatalogScreen;
/* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; /** * iOS app test suite. */ public class IOSAppTest extends SeleniumTestPlan { @Test(groups = {"verifyUICatalogScreen"}, description = "Verifies UI Catalog screen") public void verifyUICatalogScreen() throws Exception { UICatalogScreen uiCatalogScree = new UICatalogScreen(true); uiCatalogScree.clickSymbol("TextFields");
// Path: src/main/java/com/seleniumtests/core/CustomAssertion.java // public static void assertThat(final String reason, final boolean assertion) { // if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { // softAssertThat(reason, assertion); // } else { // MatcherAssert.assertThat(reason, assertion); // } // } // Path: src/test/java/com/seleniumtests/tests/IOSAppTest.java import static com.seleniumtests.core.CustomAssertion.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import org.testng.annotations.Test; import com.seleniumtests.core.SeleniumTestPlan; import com.seleniumtests.webpage.UICatalogScreen; /* * Copyright 2021 www.seleniumtests.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.seleniumtests.tests; /** * iOS app test suite. */ public class IOSAppTest extends SeleniumTestPlan { @Test(groups = {"verifyUICatalogScreen"}, description = "Verifies UI Catalog screen") public void verifyUICatalogScreen() throws Exception { UICatalogScreen uiCatalogScree = new UICatalogScreen(true); uiCatalogScree.clickSymbol("TextFields");
assertThat("UI Text Field is missing", UICatalogScreen.isUITextFieldDisplayed(), is(equalTo(true)));
tarun3kumar/seleniumtestsframework
src/main/java/com/seleniumtests/driver/DriverExceptionListener.java
// Path: src/main/java/com/seleniumtests/customexception/WebSessionEndedException.java // public class WebSessionEndedException extends WebDriverException { // // private static final long serialVersionUID = -647233887439084123L; // // public WebSessionEndedException() { // super(); // } // // public WebSessionEndedException(final Throwable ex) { // super(ex); // } // }
import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.events.WebDriverEventListener; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.customexception.WebSessionEndedException;
public void onException(final Throwable ex, final WebDriver arg1) { if (ex.getMessage() == null) { return; } else if (ex.getMessage().contains("Element must be user-editable in order to clear it")) { return; } else if (ex.getMessage().contains("Element is not clickable at point")) { return; } else if (ex instanceof UnsupportedCommandException) { return; } else if (ex.getMessage().contains(" read-only")) { return; } else if (ex.getMessage().contains("No response on ECMAScript evaluation command")) { // Opera // customexception for (int i = 0; i < ex.getStackTrace().length; i++) { final String method = ex.getStackTrace()[i].getMethodName(); if (method.contains("getTitle") || method.contains("getWindowHandle") || method.contains("click") || method.contains("getPageSource")) { return; } } ex.printStackTrace(); // return; } else if (ex.getMessage().contains("Error communicating with the remote browser. It may have died.")) { // Session has lost connection, remove it then ignore quit() method. if (WebUIDriver.getWebUIDriver().getConfig().getMode() == DriverMode.ExistingGrid) { WebUIDriver.setWebDriver(null);
// Path: src/main/java/com/seleniumtests/customexception/WebSessionEndedException.java // public class WebSessionEndedException extends WebDriverException { // // private static final long serialVersionUID = -647233887439084123L; // // public WebSessionEndedException() { // super(); // } // // public WebSessionEndedException(final Throwable ex) { // super(ex); // } // } // Path: src/main/java/com/seleniumtests/driver/DriverExceptionListener.java import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.events.WebDriverEventListener; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.customexception.WebSessionEndedException; public void onException(final Throwable ex, final WebDriver arg1) { if (ex.getMessage() == null) { return; } else if (ex.getMessage().contains("Element must be user-editable in order to clear it")) { return; } else if (ex.getMessage().contains("Element is not clickable at point")) { return; } else if (ex instanceof UnsupportedCommandException) { return; } else if (ex.getMessage().contains(" read-only")) { return; } else if (ex.getMessage().contains("No response on ECMAScript evaluation command")) { // Opera // customexception for (int i = 0; i < ex.getStackTrace().length; i++) { final String method = ex.getStackTrace()[i].getMethodName(); if (method.contains("getTitle") || method.contains("getWindowHandle") || method.contains("click") || method.contains("getPageSource")) { return; } } ex.printStackTrace(); // return; } else if (ex.getMessage().contains("Error communicating with the remote browser. It may have died.")) { // Session has lost connection, remove it then ignore quit() method. if (WebUIDriver.getWebUIDriver().getConfig().getMode() == DriverMode.ExistingGrid) { WebUIDriver.setWebDriver(null);
throw new WebSessionEndedException(ex);
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/chat/PeerClient.java
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId());
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/chat/PeerClient.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId());
connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA);
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/chat/PeerClient.java
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId());
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/chat/PeerClient.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId());
connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA);
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/chat/PeerClient.java
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId()); connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA); } catch (UnknownHostException e) { e.printStackTrace(); } peer.registerPeerListerner(new PeerReceiverListener() { @Override public void connected(Connection connection) { System.out.println(connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println("receivedMessage " + message.getConnectionID() + " : " + new String(message.getData())); if (message.getNetworkSendType() == NetworkSendType.PEER_DATA) { Object object = SerializationUtils.getInstance().deserialize(message.getData());
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/chat/PeerClient.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId()); connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA); } catch (UnknownHostException e) { e.printStackTrace(); } peer.registerPeerListerner(new PeerReceiverListener() { @Override public void connected(Connection connection) { System.out.println(connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println("receivedMessage " + message.getConnectionID() + " : " + new String(message.getData())); if (message.getNetworkSendType() == NetworkSendType.PEER_DATA) { Object object = SerializationUtils.getInstance().deserialize(message.getData());
if (object instanceof PeerList) {
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/chat/PeerClient.java
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId()); connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA); } catch (UnknownHostException e) { e.printStackTrace(); } peer.registerPeerListerner(new PeerReceiverListener() { @Override public void connected(Connection connection) { System.out.println(connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println("receivedMessage " + message.getConnectionID() + " : " + new String(message.getData())); if (message.getNetworkSendType() == NetworkSendType.PEER_DATA) { Object object = SerializationUtils.getInstance().deserialize(message.getData()); if (object instanceof PeerList) { PeerList peerList = (PeerList) object;
// Path: src/net/corpwar/lib/corpnet/master/RetrievePeerList.java // public class RetrievePeerList implements Serializable { // } // // Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/chat/PeerClient.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.RetrievePeerList; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Random; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; public class PeerClient { private PeerToPeer peer; private Random random = new Random(); public PeerClient() { peer = new PeerToPeer(); peer.startPeer(); peer.connectToPeer(20000, "127.0.0.1"); try { Connection connection = new Connection(InetAddress.getByName("127.0.0.1"), 20000); connection = peer.getPeers().get(connection.getConnectionId()); connection.addToSendQue(SerializationUtils.getInstance().serialize(new RetrievePeerList()), NetworkSendType.PEER_DATA); } catch (UnknownHostException e) { e.printStackTrace(); } peer.registerPeerListerner(new PeerReceiverListener() { @Override public void connected(Connection connection) { System.out.println(connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println("receivedMessage " + message.getConnectionID() + " : " + new String(message.getData())); if (message.getNetworkSendType() == NetworkSendType.PEER_DATA) { Object object = SerializationUtils.getInstance().deserialize(message.getData()); if (object instanceof PeerList) { PeerList peerList = (PeerList) object;
for (PeerConnected peerConnected : peerList.peerConnected) {
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/masterserver/PeerToConnect.java
// Path: src/net/corpwar/lib/corpnet/master/Peer.java // public class Peer implements Serializable{ // // // External port to peer // public int externalPort; // // // External ip to peer // public String externalIp; // // // Ping time to peer // public long ping; // // // A short description or name of the peer // public String shortName; // // // Longer description of peer // public String description; // // // Handle the connection // public UUID connectionID; // // public Peer(int externalPort, String externalIp) { // this.externalPort = externalPort; // this.externalIp = externalIp; // } // // public Peer(int externalPort, String externalIp, long ping, String shortName, String description, UUID connectionID) { // this.externalPort = externalPort; // this.externalIp = externalIp; // this.ping = ping; // this.shortName = shortName; // this.description = description; // this.connectionID = connectionID; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Peer peer = (Peer) o; // // return connectionID != null ? connectionID.equals(peer.connectionID) : peer.connectionID == null; // // } // // @Override // public int hashCode() { // return connectionID != null ? connectionID.hashCode() : 0; // } // } // // Path: src/net/corpwar/lib/corpnet/master/Peers.java // public class Peers implements Serializable { // // public List<Peer> peers; // // public Peers(List<Peer> peers) { // this.peers = peers; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.Peer; import net.corpwar.lib.corpnet.master.Peers; import java.util.Scanner; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.masterserver; public class PeerToConnect implements PeerReceiverListener { private Peers peers; private PeerToPeer peerToMaster; public PeerToConnect() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); peerToMaster.connectToMasterServer("127.0.0.1", 44444); peers = peerToMaster.retrieveMasterServerList(); if (peers != null) {
// Path: src/net/corpwar/lib/corpnet/master/Peer.java // public class Peer implements Serializable{ // // // External port to peer // public int externalPort; // // // External ip to peer // public String externalIp; // // // Ping time to peer // public long ping; // // // A short description or name of the peer // public String shortName; // // // Longer description of peer // public String description; // // // Handle the connection // public UUID connectionID; // // public Peer(int externalPort, String externalIp) { // this.externalPort = externalPort; // this.externalIp = externalIp; // } // // public Peer(int externalPort, String externalIp, long ping, String shortName, String description, UUID connectionID) { // this.externalPort = externalPort; // this.externalIp = externalIp; // this.ping = ping; // this.shortName = shortName; // this.description = description; // this.connectionID = connectionID; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Peer peer = (Peer) o; // // return connectionID != null ? connectionID.equals(peer.connectionID) : peer.connectionID == null; // // } // // @Override // public int hashCode() { // return connectionID != null ? connectionID.hashCode() : 0; // } // } // // Path: src/net/corpwar/lib/corpnet/master/Peers.java // public class Peers implements Serializable { // // public List<Peer> peers; // // public Peers(List<Peer> peers) { // this.peers = peers; // } // } // Path: test/net/corpwar/lib/corpnet/masterserver/PeerToConnect.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.Peer; import net.corpwar.lib.corpnet.master.Peers; import java.util.Scanner; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.masterserver; public class PeerToConnect implements PeerReceiverListener { private Peers peers; private PeerToPeer peerToMaster; public PeerToConnect() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); peerToMaster.connectToMasterServer("127.0.0.1", 44444); peers = peerToMaster.retrieveMasterServerList(); if (peers != null) {
for (Peer peer : peers.peers) {
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/PeerToPeer.java
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom;
// Keep the connection alive if possible private boolean keepAlive = true; // If the peer are running private boolean running = false; private byte[] buffer = new byte[bufferSize]; private ByteBuffer byteBuffer; private DatagramSocket datagramSocket = null; private DatagramPacket incoming = null; private NetworkPackage sendingPackage; private PeerToPeer.PeerThread peerThread; private Map<UUID, Connection> peers; private Connection tempConnection = new Connection(); private PeerToPeer.HandleConnection handleConnection = new PeerToPeer.HandleConnection(); private final List<PeerReceiverListener> peerReceiverListeners = new ArrayList<>(); private final Message message = new Message(); // If we want to simulate delay when we try internaly private boolean simulateDelay = false; // How much delay should we simulate private long simulateDelayTimeMin = 100, simulateDelayTimeMax = 500, simulatedDelay = 0; // Handle if connecting to a master server to handle hole punching private Connection masterServer; private Peers masterServerPeerList = null;
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/PeerToPeer.java import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; // Keep the connection alive if possible private boolean keepAlive = true; // If the peer are running private boolean running = false; private byte[] buffer = new byte[bufferSize]; private ByteBuffer byteBuffer; private DatagramSocket datagramSocket = null; private DatagramPacket incoming = null; private NetworkPackage sendingPackage; private PeerToPeer.PeerThread peerThread; private Map<UUID, Connection> peers; private Connection tempConnection = new Connection(); private PeerToPeer.HandleConnection handleConnection = new PeerToPeer.HandleConnection(); private final List<PeerReceiverListener> peerReceiverListeners = new ArrayList<>(); private final Message message = new Message(); // If we want to simulate delay when we try internaly private boolean simulateDelay = false; // How much delay should we simulate private long simulateDelayTimeMin = 100, simulateDelayTimeMax = 500, simulatedDelay = 0; // Handle if connecting to a master server to handle hole punching private Connection masterServer; private Peers masterServerPeerList = null;
private PeerList peerList = new PeerList();
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/PeerToPeer.java
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom;
} public PeerToPeer(int port, String ipAddress, int maxConnections) { this.port = port; this.ipAddress = ipAddress; byteBuffer = ByteBuffer.allocate(byteBufferSize); peers = new ConcurrentHashMap<>(maxConnections); this.maxConnections = maxConnections; protocolVersionHash = protocalVersion.hashCode(); } /** * Start server if it's not running */ public void startPeer() { if (peerThread == null || !peerThread.isAlive()) { running = true; peerThread = new PeerThread(); peerThread.start(); } if (!handleConnection.isAlive()) { handleConnection.start(); } } public void connectToPeer(int port, String ipAddress) { try { Connection connection = new Connection(InetAddress.getByName(ipAddress), port); connection.updateTime(); peers.put(connection.getConnectionId(), connection);
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/PeerToPeer.java import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; } public PeerToPeer(int port, String ipAddress, int maxConnections) { this.port = port; this.ipAddress = ipAddress; byteBuffer = ByteBuffer.allocate(byteBufferSize); peers = new ConcurrentHashMap<>(maxConnections); this.maxConnections = maxConnections; protocolVersionHash = protocalVersion.hashCode(); } /** * Start server if it's not running */ public void startPeer() { if (peerThread == null || !peerThread.isAlive()) { running = true; peerThread = new PeerThread(); peerThread.start(); } if (!handleConnection.isAlive()) { handleConnection.start(); } } public void connectToPeer(int port, String ipAddress) { try { Connection connection = new Connection(InetAddress.getByName(ipAddress), port); connection.updateTime(); peers.put(connection.getConnectionId(), connection);
connection.addToSendQue(SerializationUtils.getInstance().serialize("Knock knock peer"), NetworkSendType.PEER_DATA);
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/PeerToPeer.java
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom;
for (Connection connection : peers.values()) { long smoothTime = connection.getSmoothRoundTripTime(); for (NetworkPackage networkPackage : connection.getNetworkPackageArrayMap().values()) { if ((currentTime - networkPackage.getSentTime() - (Math.max(millisecondsBetweenResend, smoothTime) * networkPackage.getResent())) > 0) { try { networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { byteBufferResend = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); byteBufferResend.putInt(protocolVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { byteBufferResend = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); byteBufferResend.putInt(protocolVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } byte[] sendData = byteBuffer.array(); DatagramPacket dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); datagramSocket.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error resend data", e); } } } } } private synchronized void sendFromQue() { if (!running || !peerThread.isAlive() || datagramSocket == null) { return; } for (Connection connection : peers.values()) { if (connection.getNextSendQueData()) {
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/PeerToPeer.java import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; for (Connection connection : peers.values()) { long smoothTime = connection.getSmoothRoundTripTime(); for (NetworkPackage networkPackage : connection.getNetworkPackageArrayMap().values()) { if ((currentTime - networkPackage.getSentTime() - (Math.max(millisecondsBetweenResend, smoothTime) * networkPackage.getResent())) > 0) { try { networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { byteBufferResend = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); byteBufferResend.putInt(protocolVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { byteBufferResend = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); byteBufferResend.putInt(protocolVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } byte[] sendData = byteBuffer.array(); DatagramPacket dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); datagramSocket.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error resend data", e); } } } } } private synchronized void sendFromQue() { if (!running || !peerThread.isAlive() || datagramSocket == null) { return; } for (Connection connection : peers.values()) { if (connection.getNextSendQueData()) {
Iterator<SendDataQue> iter = connection.getSendDataQueList().iterator();
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/PeerToPeer.java
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom;
} } } /** * Keep all connections alive */ private synchronized void keepConnectionsAlive() { if (peerThread != null && peerThread.isAlive()) { long currentTime = System.currentTimeMillis(); for (Connection connection : peers.values()) { if (currentTime > connection.getNextKeepAlive()) { connection.addToSendQue(new byte[0], NetworkSendType.PING); connection.setNextKeepAlive(System.currentTimeMillis() + (long) (millisecondToTimeout * 0.2f)); } } } } private synchronized void removeInactiveSplitMessages() { if (peerThread != null && peerThread.isAlive()) { for (Connection connection : peers.values()) { connection.removeSplitMessages(); } } } private synchronized void sendPeerList(Connection connectingPeer) { peerList.peerConnected.clear(); for (Connection connection : peers.values()) {
// Path: src/net/corpwar/lib/corpnet/util/PeerConnected.java // public class PeerConnected implements Serializable{ // // public PeerConnected(String ipToPeer, int peerPort, long pingTime) { // this.peerPort = peerPort; // this.ipToPeer = ipToPeer; // this.pingTime = pingTime; // } // // public int peerPort; // // public String ipToPeer; // // public long pingTime; // } // // Path: src/net/corpwar/lib/corpnet/util/PeerList.java // public class PeerList implements Serializable { // // public List<PeerConnected> peerConnected = new ArrayList<>(); // // // // } // // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/PeerToPeer.java import java.util.logging.Level; import java.util.logging.Logger; import net.corpwar.lib.corpnet.master.*; import net.corpwar.lib.corpnet.util.PeerConnected; import net.corpwar.lib.corpnet.util.PeerList; import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; } } } /** * Keep all connections alive */ private synchronized void keepConnectionsAlive() { if (peerThread != null && peerThread.isAlive()) { long currentTime = System.currentTimeMillis(); for (Connection connection : peers.values()) { if (currentTime > connection.getNextKeepAlive()) { connection.addToSendQue(new byte[0], NetworkSendType.PING); connection.setNextKeepAlive(System.currentTimeMillis() + (long) (millisecondToTimeout * 0.2f)); } } } } private synchronized void removeInactiveSplitMessages() { if (peerThread != null && peerThread.isAlive()) { for (Connection connection : peers.values()) { connection.removeSplitMessages(); } } } private synchronized void sendPeerList(Connection connectingPeer) { peerList.peerConnected.clear(); for (Connection connection : peers.values()) {
peerList.peerConnected.add(new PeerConnected(connection.getAddress().getHostAddress(), connection.getPort(), connection.getSmoothRoundTripTime()));
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/masterserver/PeerNatServerTest.java
// Path: src/net/corpwar/lib/corpnet/master/TestMessage.java // public class TestMessage implements Serializable { // // public String testMessage = "This is a test message to test NAT"; // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.TestMessage; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.util.UUID;
package net.corpwar.lib.corpnet.masterserver; /** * corpnet * Created by Ghost on 2016-12-15. */ public class PeerNatServerTest implements PeerReceiverListener { private PeerToPeer peerToMaster; public PeerNatServerTest() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); System.out.println("Nat test client started"); peerToMaster.connectToMasterServer("127.0.0.1", 44444); System.out.println("Peer amount: " + peerToMaster.getPeers().size()); peerToMaster.testNatViaMasterServer(); } @Override public void connected(Connection connection) { System.out.println("Connected: " + connection.getConnectionId() + " " + connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println(new String(message.getData()) + "\nPeer amount: " + peerToMaster.getPeers().size());
// Path: src/net/corpwar/lib/corpnet/master/TestMessage.java // public class TestMessage implements Serializable { // // public String testMessage = "This is a test message to test NAT"; // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/masterserver/PeerNatServerTest.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.TestMessage; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.util.UUID; package net.corpwar.lib.corpnet.masterserver; /** * corpnet * Created by Ghost on 2016-12-15. */ public class PeerNatServerTest implements PeerReceiverListener { private PeerToPeer peerToMaster; public PeerNatServerTest() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); System.out.println("Nat test client started"); peerToMaster.connectToMasterServer("127.0.0.1", 44444); System.out.println("Peer amount: " + peerToMaster.getPeers().size()); peerToMaster.testNatViaMasterServer(); } @Override public void connected(Connection connection) { System.out.println("Connected: " + connection.getConnectionId() + " " + connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println(new String(message.getData()) + "\nPeer amount: " + peerToMaster.getPeers().size());
peerToMaster.getPeers().get(message.getConnectionID()).addToSendQue(SerializationUtils.getInstance().serialize(new TestMessage()), NetworkSendType.PEER_DATA);
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/masterserver/PeerNatServerTest.java
// Path: src/net/corpwar/lib/corpnet/master/TestMessage.java // public class TestMessage implements Serializable { // // public String testMessage = "This is a test message to test NAT"; // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.TestMessage; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.util.UUID;
package net.corpwar.lib.corpnet.masterserver; /** * corpnet * Created by Ghost on 2016-12-15. */ public class PeerNatServerTest implements PeerReceiverListener { private PeerToPeer peerToMaster; public PeerNatServerTest() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); System.out.println("Nat test client started"); peerToMaster.connectToMasterServer("127.0.0.1", 44444); System.out.println("Peer amount: " + peerToMaster.getPeers().size()); peerToMaster.testNatViaMasterServer(); } @Override public void connected(Connection connection) { System.out.println("Connected: " + connection.getConnectionId() + " " + connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println(new String(message.getData()) + "\nPeer amount: " + peerToMaster.getPeers().size());
// Path: src/net/corpwar/lib/corpnet/master/TestMessage.java // public class TestMessage implements Serializable { // // public String testMessage = "This is a test message to test NAT"; // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/masterserver/PeerNatServerTest.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.master.TestMessage; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.util.UUID; package net.corpwar.lib.corpnet.masterserver; /** * corpnet * Created by Ghost on 2016-12-15. */ public class PeerNatServerTest implements PeerReceiverListener { private PeerToPeer peerToMaster; public PeerNatServerTest() { peerToMaster = new PeerToPeer(); peerToMaster.registerPeerListerner(this); peerToMaster.startPeer(); System.out.println("Nat test client started"); peerToMaster.connectToMasterServer("127.0.0.1", 44444); System.out.println("Peer amount: " + peerToMaster.getPeers().size()); peerToMaster.testNatViaMasterServer(); } @Override public void connected(Connection connection) { System.out.println("Connected: " + connection.getConnectionId() + " " + connection.getAddress().getHostAddress() + ":" + connection.getPort()); } @Override public void receivedMessage(Message message) { System.out.println(new String(message.getData()) + "\nPeer amount: " + peerToMaster.getPeers().size());
peerToMaster.getPeers().get(message.getConnectionID()).addToSendQue(SerializationUtils.getInstance().serialize(new TestMessage()), NetworkSendType.PEER_DATA);
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/Server.java
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger;
* Start server if it's not running */ public void startServer() { if (serverThread == null || !serverThread.isAlive()) { running = true; serverThread = new ServerThread(); serverThread.start(); } if (!handleConnection.isAlive()) { handleConnection.start(); } } /** * Kill the server if it's running */ public void killServer() { if (serverThread.isAlive() ) { running = false; datagramSocket.close(); serverThread.interrupt(); handleConnection.interrupt(); } } /** * Send an unreliable message to all clients that is connected * @param sendObject */ public <T> void sendUnreliableObjectToAllClients(T sendObject) {
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/Server.java import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; * Start server if it's not running */ public void startServer() { if (serverThread == null || !serverThread.isAlive()) { running = true; serverThread = new ServerThread(); serverThread.start(); } if (!handleConnection.isAlive()) { handleConnection.start(); } } /** * Kill the server if it's running */ public void killServer() { if (serverThread.isAlive() ) { running = false; datagramSocket.close(); serverThread.interrupt(); handleConnection.interrupt(); } } /** * Send an unreliable message to all clients that is connected * @param sendObject */ public <T> void sendUnreliableObjectToAllClients(T sendObject) {
sendUnreliableToAllClients(SerializationUtils.getInstance().serialize(sendObject));
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/Server.java
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger;
networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { byteBufferResend = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); byteBufferResend.putInt(protocalVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { byteBufferResend = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); byteBufferResend.putInt(protocalVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } byte[] sendData = byteBuffer.array(); DatagramPacket dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); datagramSocket.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error resend data", e); } } } } } public synchronized void sendFromQue() { if (!running || !serverThread.isAlive() || datagramSocket == null) { return; } for (Connection connection : clients.values()) { sendFromQueConnection(connection); } } private synchronized void sendFromQueConnection(Connection connection) { if (connection.getNextSendQueData()) {
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/Server.java import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { byteBufferResend = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); byteBufferResend.putInt(protocalVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { byteBufferResend = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); byteBufferResend.putInt(protocalVersionHash).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } byte[] sendData = byteBuffer.array(); DatagramPacket dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); datagramSocket.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error resend data", e); } } } } } public synchronized void sendFromQue() { if (!running || !serverThread.isAlive() || datagramSocket == null) { return; } for (Connection connection : clients.values()) { sendFromQueConnection(connection); } } private synchronized void sendFromQueConnection(Connection connection) { if (connection.getNextSendQueData()) {
Iterator<SendDataQue> iter = connection.getSendDataQueList().iterator();
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/util/SendDataQue.java
// Path: src/net/corpwar/lib/corpnet/NetworkSendType.java // public enum NetworkSendType { // // // If something went wrong use this // ERROR(-1), // // // Notification that the reliable packed was sent correctly // ACK(0), // // // Send an integer where in the que the client are // QUENUMBER(1), // // // Send an init signal to establish an connection // INITSIGNAL(2), // // // Send reliable game data between server and client // RELIABLE_GAME_DATA(20), // // // Send unreliable game data between server and client // UNRELIABLE_GAME_DATA(21), // // // Send data about peers // PEER_DATA(22), // // // Send a split reliable message, all parts will be delivered // RELIABLE_SPLIT_GAME_DATA(30), // // // Send a split unreliable message, if any part of the message are lost all of the message will be discarded // // If the packages are getting in the wrong order the message will be discarded // UNRELIABLE_SPLIT_GAME_DATA(31), // // PEER_SPLIT_DATA(32), // // // If you just need to ping and tell you are alive, Or for testing // PING(100); // // private int typeCode; // // private NetworkSendType(int tp) { // typeCode = tp; // } // // public int getTypeCode() { // return typeCode; // } // // public static NetworkSendType fromByteValue(byte type) { // switch (type) { // case 0: // return ACK; // case 1: // return QUENUMBER; // case 2: // return INITSIGNAL; // case 20: // return RELIABLE_GAME_DATA; // case 21: // return UNRELIABLE_GAME_DATA; // case 22: // return PEER_DATA; // case 30: // return RELIABLE_SPLIT_GAME_DATA; // case 31: // return UNRELIABLE_SPLIT_GAME_DATA; // case 32: // return PEER_SPLIT_DATA; // case 100: // return PING; // default: // return ERROR; // } // } // }
import net.corpwar.lib.corpnet.NetworkSendType;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.util; public class SendDataQue { // Data to send private byte[] aByte; // What kind of message to send
// Path: src/net/corpwar/lib/corpnet/NetworkSendType.java // public enum NetworkSendType { // // // If something went wrong use this // ERROR(-1), // // // Notification that the reliable packed was sent correctly // ACK(0), // // // Send an integer where in the que the client are // QUENUMBER(1), // // // Send an init signal to establish an connection // INITSIGNAL(2), // // // Send reliable game data between server and client // RELIABLE_GAME_DATA(20), // // // Send unreliable game data between server and client // UNRELIABLE_GAME_DATA(21), // // // Send data about peers // PEER_DATA(22), // // // Send a split reliable message, all parts will be delivered // RELIABLE_SPLIT_GAME_DATA(30), // // // Send a split unreliable message, if any part of the message are lost all of the message will be discarded // // If the packages are getting in the wrong order the message will be discarded // UNRELIABLE_SPLIT_GAME_DATA(31), // // PEER_SPLIT_DATA(32), // // // If you just need to ping and tell you are alive, Or for testing // PING(100); // // private int typeCode; // // private NetworkSendType(int tp) { // typeCode = tp; // } // // public int getTypeCode() { // return typeCode; // } // // public static NetworkSendType fromByteValue(byte type) { // switch (type) { // case 0: // return ACK; // case 1: // return QUENUMBER; // case 2: // return INITSIGNAL; // case 20: // return RELIABLE_GAME_DATA; // case 21: // return UNRELIABLE_GAME_DATA; // case 22: // return PEER_DATA; // case 30: // return RELIABLE_SPLIT_GAME_DATA; // case 31: // return UNRELIABLE_SPLIT_GAME_DATA; // case 32: // return PEER_SPLIT_DATA; // case 100: // return PING; // default: // return ERROR; // } // } // } // Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java import net.corpwar.lib.corpnet.NetworkSendType; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.util; public class SendDataQue { // Data to send private byte[] aByte; // What kind of message to send
private NetworkSendType networkSendType;
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/masterserver/MasterServerTest.java
// Path: src/net/corpwar/lib/corpnet/master/MasterServer.java // public class MasterServer implements DataReceivedListener { // // private static final Logger LOG = Logger.getLogger(MasterServer.class.getName()); // // // Primary server to register to // private Server masterServer; // // // Port on master server // private int port; // // // IP on master server // private String ipAddress; // // // Max connections on master server // private int maxConnections; // // // Secondary server to try for symmetric NAT // private PeerToPeer peerNatTestServer; // // // All the peers that can be connected to // private List<Peer> peers = new ArrayList<>(); // // private Boolean testSymmetricNat = false; // // // public MasterServer() { // port = 44444; // ipAddress = "127.0.0.1"; // maxConnections = 8; // } // // public MasterServer(String ipAddress, int port, int maxConnections) { // this.port = port; // this.ipAddress = ipAddress; // this.maxConnections = maxConnections; // } // // public void startMasterServer(boolean testSymmetricNat) { // masterServer = new Server(port, ipAddress, maxConnections); // masterServer.registerServerListerner(this); // masterServer.startServer(); // this.testSymmetricNat = testSymmetricNat; // if (this.testSymmetricNat) { // peerNatTestServer = new PeerToPeer(port + 1, ipAddress, maxConnections); // peerNatTestServer.registerPeerListerner(new NATTestServer()); // peerNatTestServer.startPeer(); // } // } // // public Server getMasterServer() { // return masterServer; // } // // @Override // public void connected(Connection connection) { // // } // // @Override // public void receivedMessage(Message message) { // if (message.getNetworkSendType().equals(NetworkSendType.PEER_DATA)) { // if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof RegisterPeer) { // RegisterPeer registerPeer = SerializationUtils.getInstance().deserialize(message.getData()); // Connection connection = masterServer.getConnectionFromUUID(message.getConnectionID()); // Peer peer = new Peer(connection.getPort(), connection.getAddress().getHostAddress(), connection.getLastPingTime(), registerPeer.shortName, registerPeer.description, message.getConnectionID()); // peers.add(peer); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof RetrievePeerList) { // Connection connection = masterServer.getConnectionFromUUID(message.getConnectionID()); // connection.addToSendQue(SerializationUtils.getInstance().serialize(new Peers(peers)), NetworkSendType.PEER_DATA); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof ConnectToPeer) { // ConnectToPeer connectToPeer = SerializationUtils.getInstance().deserialize(message.getData()); // Connection connection = masterServer.getConnectionFromUUID(connectToPeer.connectionID); // Connection askingPeer = masterServer.getConnectionFromUUID(message.getConnectionID()); // connection.addToSendQue(SerializationUtils.getInstance().serialize(new ConnectToPeer(askingPeer.getPort(), askingPeer.getAddress().getHostAddress())), NetworkSendType.PEER_DATA); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof TestNat) { // if (testSymmetricNat) { // Connection askingPeer = masterServer.getConnectionFromUUID(message.getConnectionID()); // peerNatTestServer.connectToPeer(askingPeer.getPort(), askingPeer.getAddress().getHostAddress()); // } else { // masterServer.getConnectionFromUUID(message.getConnectionID()).addToSendQue(SerializationUtils.getInstance().serialize("No test nat server up"), NetworkSendType.PEER_DATA); // } // } // } // } // // @Override // public void disconnected(UUID connectionId) { // for (Peer peer : peers) { // if (peer.connectionID.equals(connectionId)) { // peers.remove(peer); // break; // } // } // } // // class NATTestServer implements PeerReceiverListener { // // @Override // public void connected(Connection connection) { // // } // // @Override // public void receivedMessage(Message message) { // System.out.println("NATTestServer receivedMessage: " + new String(message.getData())); // } // // @Override // public void disconnected(UUID connectionId) { // // } // } // }
import net.corpwar.lib.corpnet.master.MasterServer;
/************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.masterserver; public class MasterServerTest { public MasterServerTest() {
// Path: src/net/corpwar/lib/corpnet/master/MasterServer.java // public class MasterServer implements DataReceivedListener { // // private static final Logger LOG = Logger.getLogger(MasterServer.class.getName()); // // // Primary server to register to // private Server masterServer; // // // Port on master server // private int port; // // // IP on master server // private String ipAddress; // // // Max connections on master server // private int maxConnections; // // // Secondary server to try for symmetric NAT // private PeerToPeer peerNatTestServer; // // // All the peers that can be connected to // private List<Peer> peers = new ArrayList<>(); // // private Boolean testSymmetricNat = false; // // // public MasterServer() { // port = 44444; // ipAddress = "127.0.0.1"; // maxConnections = 8; // } // // public MasterServer(String ipAddress, int port, int maxConnections) { // this.port = port; // this.ipAddress = ipAddress; // this.maxConnections = maxConnections; // } // // public void startMasterServer(boolean testSymmetricNat) { // masterServer = new Server(port, ipAddress, maxConnections); // masterServer.registerServerListerner(this); // masterServer.startServer(); // this.testSymmetricNat = testSymmetricNat; // if (this.testSymmetricNat) { // peerNatTestServer = new PeerToPeer(port + 1, ipAddress, maxConnections); // peerNatTestServer.registerPeerListerner(new NATTestServer()); // peerNatTestServer.startPeer(); // } // } // // public Server getMasterServer() { // return masterServer; // } // // @Override // public void connected(Connection connection) { // // } // // @Override // public void receivedMessage(Message message) { // if (message.getNetworkSendType().equals(NetworkSendType.PEER_DATA)) { // if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof RegisterPeer) { // RegisterPeer registerPeer = SerializationUtils.getInstance().deserialize(message.getData()); // Connection connection = masterServer.getConnectionFromUUID(message.getConnectionID()); // Peer peer = new Peer(connection.getPort(), connection.getAddress().getHostAddress(), connection.getLastPingTime(), registerPeer.shortName, registerPeer.description, message.getConnectionID()); // peers.add(peer); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof RetrievePeerList) { // Connection connection = masterServer.getConnectionFromUUID(message.getConnectionID()); // connection.addToSendQue(SerializationUtils.getInstance().serialize(new Peers(peers)), NetworkSendType.PEER_DATA); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof ConnectToPeer) { // ConnectToPeer connectToPeer = SerializationUtils.getInstance().deserialize(message.getData()); // Connection connection = masterServer.getConnectionFromUUID(connectToPeer.connectionID); // Connection askingPeer = masterServer.getConnectionFromUUID(message.getConnectionID()); // connection.addToSendQue(SerializationUtils.getInstance().serialize(new ConnectToPeer(askingPeer.getPort(), askingPeer.getAddress().getHostAddress())), NetworkSendType.PEER_DATA); // } else if (SerializationUtils.getInstance().deserialize(message.getData()) instanceof TestNat) { // if (testSymmetricNat) { // Connection askingPeer = masterServer.getConnectionFromUUID(message.getConnectionID()); // peerNatTestServer.connectToPeer(askingPeer.getPort(), askingPeer.getAddress().getHostAddress()); // } else { // masterServer.getConnectionFromUUID(message.getConnectionID()).addToSendQue(SerializationUtils.getInstance().serialize("No test nat server up"), NetworkSendType.PEER_DATA); // } // } // } // } // // @Override // public void disconnected(UUID connectionId) { // for (Peer peer : peers) { // if (peer.connectionID.equals(connectionId)) { // peers.remove(peer); // break; // } // } // } // // class NATTestServer implements PeerReceiverListener { // // @Override // public void connected(Connection connection) { // // } // // @Override // public void receivedMessage(Message message) { // System.out.println("NATTestServer receivedMessage: " + new String(message.getData())); // } // // @Override // public void disconnected(UUID connectionId) { // // } // } // } // Path: test/net/corpwar/lib/corpnet/masterserver/MasterServerTest.java import net.corpwar.lib.corpnet.master.MasterServer; /************************************************************************** * CorpNet * Copyright (C) 2016 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.masterserver; public class MasterServerTest { public MasterServerTest() {
MasterServer masterServer = new MasterServer();
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/Client.java
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.math.BigInteger; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger;
* Switch simulated delay on and of * @param simulateDelay */ public void setSimulateDelay(boolean simulateDelay) { this.simulateDelay = simulateDelay; simulatedDelay = ThreadLocalRandom.current().nextLong(simulateDelayTimeMin, simulateDelayTimeMax); } /** * Set how much simulated delay should be used * @param simulateDelayTimeMin * @param simulateDelayTimeMax */ public void setSimulateDelayTime(long simulateDelayTimeMin, long simulateDelayTimeMax) { this.simulateDelayTimeMin = simulateDelayTimeMin; this.simulateDelayTimeMax = simulateDelayTimeMax; } /** * Send a ping to server to check if it is there */ public void sendPing() { connection.addToSendQue(new byte[0], NetworkSendType.PING); } /** * Send an unreliable object to server. Just a simpler way then send a byte[] * @param sendObjct */ public <T> void sendUnreliableDataObject(T sendObjct) {
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/Client.java import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.math.BigInteger; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; * Switch simulated delay on and of * @param simulateDelay */ public void setSimulateDelay(boolean simulateDelay) { this.simulateDelay = simulateDelay; simulatedDelay = ThreadLocalRandom.current().nextLong(simulateDelayTimeMin, simulateDelayTimeMax); } /** * Set how much simulated delay should be used * @param simulateDelayTimeMin * @param simulateDelayTimeMax */ public void setSimulateDelayTime(long simulateDelayTimeMin, long simulateDelayTimeMax) { this.simulateDelayTimeMin = simulateDelayTimeMin; this.simulateDelayTimeMax = simulateDelayTimeMax; } /** * Send a ping to server to check if it is there */ public void sendPing() { connection.addToSendQue(new byte[0], NetworkSendType.PING); } /** * Send an unreliable object to server. Just a simpler way then send a byte[] * @param sendObjct */ public <T> void sendUnreliableDataObject(T sendObjct) {
sendUnreliableData(SerializationUtils.getInstance().serialize(sendObjct));
CorpWar/CorpNet
src/net/corpwar/lib/corpnet/Client.java
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.math.BigInteger; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger;
long smoothTime = connection.getSmoothRoundTripTime(); for (NetworkPackage networkPackage : connection.getNetworkPackageArrayMap().values()) { if ((currentTime - networkPackage.getSentTime() - Math.max(millisecondsBetweenResend, smoothTime * networkPackage.getResent())) > 0) { System.out.println("RESEND! : " + networkPackage.getSequenceNumber()); try { networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { resendByteBuffer = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); resendByteBuffer.putInt(protocalVersion).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { resendByteBuffer = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); resendByteBuffer.putInt(protocalVersion).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } sendData = resendByteBuffer.array(); dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); sock.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error send data", e); } } } } private synchronized void sendFromQue() { if (!running || !clientThread.isAlive() || sock == null) { return; } if (connection.getNextSendQueData()) {
// Path: src/net/corpwar/lib/corpnet/util/SendDataQue.java // public class SendDataQue { // // // Data to send // private byte[] aByte; // // // What kind of message to send // private NetworkSendType networkSendType; // // // When this data was added for sending // private long addedTime; // // public SendDataQue() { // } // // public SendDataQue setValues(byte[] bytes, NetworkSendType networkSendType) { // this.aByte = bytes; // this.networkSendType = networkSendType; // this.addedTime = System.currentTimeMillis(); // return this; // } // // public byte[] getaByte() { // return aByte; // } // // public NetworkSendType getNetworkSendType() { // return networkSendType; // } // // public long getAddedTime() { // return addedTime; // } // } // // Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: src/net/corpwar/lib/corpnet/Client.java import net.corpwar.lib.corpnet.util.SendDataQue; import net.corpwar.lib.corpnet.util.SerializationUtils; import java.io.IOException; import java.math.BigInteger; import java.net.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; long smoothTime = connection.getSmoothRoundTripTime(); for (NetworkPackage networkPackage : connection.getNetworkPackageArrayMap().values()) { if ((currentTime - networkPackage.getSentTime() - Math.max(millisecondsBetweenResend, smoothTime * networkPackage.getResent())) > 0) { System.out.println("RESEND! : " + networkPackage.getSequenceNumber()); try { networkPackage.resendData(networkPackage.getSequenceNumber()); if (networkPackage.getNetworkSendType() == NetworkSendType.RELIABLE_SPLIT_GAME_DATA) { resendByteBuffer = ByteBuffer.allocate(byteBufferSize + 4 + networkPackage.getDataSent().length); resendByteBuffer.putInt(protocalVersion).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).putInt(networkPackage.getSplitSequenceNumber()).put(networkPackage.getDataSent()); } else { resendByteBuffer = ByteBuffer.allocate(byteBufferSize + networkPackage.getDataSent().length); resendByteBuffer.putInt(protocalVersion).put((byte) networkPackage.getNetworkSendType().getTypeCode()).putInt(networkPackage.getSequenceNumber()).put(networkPackage.getDataSent()); } sendData = resendByteBuffer.array(); dp = new DatagramPacket(sendData, sendData.length, connection.getAddress(), connection.getPort()); sock.send(dp); } catch (IOException e) { LOG.log(Level.SEVERE, "Error send data", e); } } } } private synchronized void sendFromQue() { if (!running || !clientThread.isAlive() || sock == null) { return; } if (connection.getNextSendQueData()) {
Iterator<SendDataQue> iter = connection.getSendDataQueList().iterator();
CorpWar/CorpNet
test/net/corpwar/lib/corpnet/chat/ChatServer.java
// Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // }
import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.util.SerializationUtils; import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.UUID;
/************************************************************************** * CorpNet * Copyright (C) 2014 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; /** * corpnet * Created by Ghost on 2014-12-13. */ public class ChatServer { private Server server; private Classes.SendMessage sendMessage = new Classes.SendMessage(); public ChatServer() { server = new Server(); server.setKeepAlive(true); server.startServer(); server.registerServerListerner(new DataReceivedListener() { @Override public void connected(Connection connection) { } @Override public void receivedMessage(Message message) {
// Path: src/net/corpwar/lib/corpnet/util/SerializationUtils.java // public class SerializationUtils { // // private static SerializationUtils serializationUtils = null; // private static final Logger LOG = Logger.getLogger(SerializationUtils.class.getName()); // private static final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // // private SerializationUtils() { // } // // public static SerializationUtils getInstance() { // if (serializationUtils == null) { // serializationUtils = new SerializationUtils(); // } // return serializationUtils; // } // // public <T> byte[] serialize(T obj) { // ObjectOutputStream oos = null; // try { // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // oos.reset(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } finally { // if (oos != null) { // try { // oos.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // byte[] byteObj = baos.toByteArray(); // baos.reset(); // return byteObj; // } // // public <T> T deserialize(byte[] bytes) { // T obj = null; // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // try { // bais = new ByteArrayInputStream(bytes); // ois = new ObjectInputStream(bais); // obj = (T) ois.readObject(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } catch (ClassNotFoundException e) { // LOG.log(Level.SEVERE, "Error Class not found", e); // return null; // } finally { // if (ois != null) { // try { // ois.close(); // } catch (IOException e) { // LOG.log(Level.SEVERE, "Error IOException", e); // } // } // } // return obj; // } // } // Path: test/net/corpwar/lib/corpnet/chat/ChatServer.java import net.corpwar.lib.corpnet.*; import net.corpwar.lib.corpnet.util.SerializationUtils; import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.UUID; /************************************************************************** * CorpNet * Copyright (C) 2014 Daniel Ekedahl * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ package net.corpwar.lib.corpnet.chat; /** * corpnet * Created by Ghost on 2014-12-13. */ public class ChatServer { private Server server; private Classes.SendMessage sendMessage = new Classes.SendMessage(); public ChatServer() { server = new Server(); server.setKeepAlive(true); server.startServer(); server.registerServerListerner(new DataReceivedListener() { @Override public void connected(Connection connection) { } @Override public void receivedMessage(Message message) {
Object obj = SerializationUtils.getInstance().deserialize(message.getData());
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java
// Path: src/main/java/com/healthmarketscience/rmiio/util/InputStreamAdapter.java // public abstract class InputStreamAdapter // { // // private InputStreamAdapter() { // } // // /** // * @return the underlying InputStream // */ // public abstract InputStream getInputStream(); // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method will probably block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). // * <p> // * Note, this method is slightly optimized for current usage, so an // * implementation caveat is that the returned packet must be "consumed" // * before another call to readPacket is made. // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public abstract byte[] readPacket() throws IOException; // // /** // * @return a buffer containing the bytes read by the last successful // * {@link #readTemp} call // */ // public abstract byte[] getTempBuffer(); // // /** // * Reads some number of bytes from the underlying stream and puts them in a // * buffer available from the {@link #getTempBuffer} call. // * // * @return the number of bytes read, or -1 if end of stream was reached // */ // public abstract int readTemp() throws IOException; // // /** // * @param istream stream to wrap and for which the implementation is // * optimized // * @param packetSize recommended packet size for any created packets // * @return a new InputStreamAdapter optimized for the stream type // */ // public static InputStreamAdapter create(InputStream istream, int packetSize) // { // if(istream instanceof PacketInputStream) { // return new PacketAdapter((PacketInputStream)istream); // } // return new DefaultAdapter(istream, packetSize); // } // // /** // * InputStreamAdapter implementation for PacketInputStreams. // */ // private static class PacketAdapter extends InputStreamAdapter // { // private final PacketInputStream _pistream; // /** the last packet returned during a readTemp call */ // private byte[] _temp; // // private PacketAdapter(PacketInputStream pistream) { // _pistream = pistream; // } // // @Override // public PacketInputStream getInputStream() { return _pistream; } // // @Override // public byte[] readPacket() throws IOException { // return _pistream.readPacket(); // } // // @Override // public byte[] getTempBuffer() { // return _temp; // } // // @Override // public int readTemp() throws IOException { // _temp = _pistream.readPacket(); // return((_temp != null) ? _temp.length : -1); // } // // } // // /** // * InputStreamAdapter implementation for normal InputStreams. // */ // private static class DefaultAdapter extends InputStreamAdapter // { // private final InputStream _istream; // /** temporary buffer for reading data from the underlying InputStream */ // private final byte[] _temp; // // private DefaultAdapter(InputStream istream, int packetSize) { // _istream = istream; // _temp = new byte[packetSize]; // } // // @Override // public InputStream getInputStream() { return _istream; } // // @Override // public byte[] readPacket() throws IOException { // return PacketInputStream.readPacket(_istream, _temp); // } // // @Override // public byte[] getTempBuffer() { // return _temp; // } // // @Override // public int readTemp() throws IOException { // return _istream.read(_temp, 0, _temp.length); // } // // } // // }
import java.io.IOException; import java.io.InputStream; import com.healthmarketscience.rmiio.util.InputStreamAdapter;
/* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio; /** * Concrete implementation of a RemoteInputStreamServer which sends * uncompressed data, which it will read directly from the underlying * InputStream. * * @see <a href="{@docRoot}/overview-summary.html#Usage_Notes">Usage Notes</a> * @see #writeReplace * * @author James Ahlborn */ public class SimpleRemoteInputStream extends RemoteInputStreamServer { private static final long serialVersionUID = 20080212L; /** manages reading from the given stream in a packet-like manner */
// Path: src/main/java/com/healthmarketscience/rmiio/util/InputStreamAdapter.java // public abstract class InputStreamAdapter // { // // private InputStreamAdapter() { // } // // /** // * @return the underlying InputStream // */ // public abstract InputStream getInputStream(); // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method will probably block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). // * <p> // * Note, this method is slightly optimized for current usage, so an // * implementation caveat is that the returned packet must be "consumed" // * before another call to readPacket is made. // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public abstract byte[] readPacket() throws IOException; // // /** // * @return a buffer containing the bytes read by the last successful // * {@link #readTemp} call // */ // public abstract byte[] getTempBuffer(); // // /** // * Reads some number of bytes from the underlying stream and puts them in a // * buffer available from the {@link #getTempBuffer} call. // * // * @return the number of bytes read, or -1 if end of stream was reached // */ // public abstract int readTemp() throws IOException; // // /** // * @param istream stream to wrap and for which the implementation is // * optimized // * @param packetSize recommended packet size for any created packets // * @return a new InputStreamAdapter optimized for the stream type // */ // public static InputStreamAdapter create(InputStream istream, int packetSize) // { // if(istream instanceof PacketInputStream) { // return new PacketAdapter((PacketInputStream)istream); // } // return new DefaultAdapter(istream, packetSize); // } // // /** // * InputStreamAdapter implementation for PacketInputStreams. // */ // private static class PacketAdapter extends InputStreamAdapter // { // private final PacketInputStream _pistream; // /** the last packet returned during a readTemp call */ // private byte[] _temp; // // private PacketAdapter(PacketInputStream pistream) { // _pistream = pistream; // } // // @Override // public PacketInputStream getInputStream() { return _pistream; } // // @Override // public byte[] readPacket() throws IOException { // return _pistream.readPacket(); // } // // @Override // public byte[] getTempBuffer() { // return _temp; // } // // @Override // public int readTemp() throws IOException { // _temp = _pistream.readPacket(); // return((_temp != null) ? _temp.length : -1); // } // // } // // /** // * InputStreamAdapter implementation for normal InputStreams. // */ // private static class DefaultAdapter extends InputStreamAdapter // { // private final InputStream _istream; // /** temporary buffer for reading data from the underlying InputStream */ // private final byte[] _temp; // // private DefaultAdapter(InputStream istream, int packetSize) { // _istream = istream; // _temp = new byte[packetSize]; // } // // @Override // public InputStream getInputStream() { return _istream; } // // @Override // public byte[] readPacket() throws IOException { // return PacketInputStream.readPacket(_istream, _temp); // } // // @Override // public byte[] getTempBuffer() { // return _temp; // } // // @Override // public int readTemp() throws IOException { // return _istream.read(_temp, 0, _temp.length); // } // // } // // } // Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java import java.io.IOException; import java.io.InputStream; import com.healthmarketscience.rmiio.util.InputStreamAdapter; /* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio; /** * Concrete implementation of a RemoteInputStreamServer which sends * uncompressed data, which it will read directly from the underlying * InputStream. * * @see <a href="{@docRoot}/overview-summary.html#Usage_Notes">Usage Notes</a> * @see #writeReplace * * @author James Ahlborn */ public class SimpleRemoteInputStream extends RemoteInputStreamServer { private static final long serialVersionUID = 20080212L; /** manages reading from the given stream in a packet-like manner */
private transient final InputStreamAdapter _inAdapter;
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/util/InputStreamAdapter.java
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // }
import java.io.IOException; import java.io.InputStream; import com.healthmarketscience.rmiio.PacketInputStream;
/* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio.util; /** * Utility class for optimizing different read strategies based on the type of * the underlying InputStream. * * @author James Ahlborn */ public abstract class InputStreamAdapter { private InputStreamAdapter() { } /** * @return the underlying InputStream */ public abstract InputStream getInputStream(); /** * Gets the next "packet" from the internal buffer and returns it (if any). * This method will probably block until a fully filled packet is created * (equivalent to calling <code>readPacket(false)</code>). * <p> * Note, this method is slightly optimized for current usage, so an * implementation caveat is that the returned packet must be "consumed" * before another call to readPacket is made. * * @return a fully filled array of byte's or <code>null</code> if the end of * stream has been reached */ public abstract byte[] readPacket() throws IOException; /** * @return a buffer containing the bytes read by the last successful * {@link #readTemp} call */ public abstract byte[] getTempBuffer(); /** * Reads some number of bytes from the underlying stream and puts them in a * buffer available from the {@link #getTempBuffer} call. * * @return the number of bytes read, or -1 if end of stream was reached */ public abstract int readTemp() throws IOException; /** * @param istream stream to wrap and for which the implementation is * optimized * @param packetSize recommended packet size for any created packets * @return a new InputStreamAdapter optimized for the stream type */ public static InputStreamAdapter create(InputStream istream, int packetSize) {
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // } // Path: src/main/java/com/healthmarketscience/rmiio/util/InputStreamAdapter.java import java.io.IOException; import java.io.InputStream; import com.healthmarketscience.rmiio.PacketInputStream; /* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio.util; /** * Utility class for optimizing different read strategies based on the type of * the underlying InputStream. * * @author James Ahlborn */ public abstract class InputStreamAdapter { private InputStreamAdapter() { } /** * @return the underlying InputStream */ public abstract InputStream getInputStream(); /** * Gets the next "packet" from the internal buffer and returns it (if any). * This method will probably block until a fully filled packet is created * (equivalent to calling <code>readPacket(false)</code>). * <p> * Note, this method is slightly optimized for current usage, so an * implementation caveat is that the returned packet must be "consumed" * before another call to readPacket is made. * * @return a fully filled array of byte's or <code>null</code> if the end of * stream has been reached */ public abstract byte[] readPacket() throws IOException; /** * @return a buffer containing the bytes read by the last successful * {@link #readTemp} call */ public abstract byte[] getTempBuffer(); /** * Reads some number of bytes from the underlying stream and puts them in a * buffer available from the {@link #getTempBuffer} call. * * @return the number of bytes read, or -1 if end of stream was reached */ public abstract int readTemp() throws IOException; /** * @param istream stream to wrap and for which the implementation is * optimized * @param packetSize recommended packet size for any created packets * @return a new InputStreamAdapter optimized for the stream type */ public static InputStreamAdapter create(InputStream istream, int packetSize) {
if(istream instanceof PacketInputStream) {
jahlborn/rmiio
src/corbaExample/src/java/examples/iiop/TestClient.java
// Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java // public class SimpleRemoteInputStream extends RemoteInputStreamServer // { // private static final long serialVersionUID = 20080212L; // // /** manages reading from the given stream in a packet-like manner */ // private transient final InputStreamAdapter _inAdapter; // // public SimpleRemoteInputStream(InputStream in) { // this(in, DUMMY_MONITOR, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor) { // this(in, monitor, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor, // int chunkSize) // { // super(in, monitor, chunkSize); // _inAdapter = InputStreamAdapter.create(in, _chunkSize); // } // // @Override // public boolean usingGZIPCompression() // { // // no compression // return false; // } // // @Override // protected int availableImpl() // throws IOException // { // synchronized(getLock()) { // return _in.available(); // } // } // // @Override // protected byte[] readPacket() // throws IOException // { // // will be called synchronized // // // read another packet of data // byte[] packet = _inAdapter.readPacket(); // if(packet != null) { // _monitor.localBytesMoved(this, packet.length); // } // return packet; // } // // @Override // protected long skip(long n) // throws IOException // { // // will be called synchronized // long numSkipped = _in.skip(n); // _monitor.localBytesSkipped(this, numSkipped); // return numSkipped; // } // // }
import java.io.FileInputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import com.healthmarketscience.rmiio.SimpleRemoteInputStream;
/* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iiop; /** * Example corba client which sends a file (given on the command line) to the * example server using a RemoteInputStream. * * @author James Ahlborn */ public class TestClient { public static void main(String[] args) throws Exception { if(args.length < 1) { System.err.println("Usage: <file>"); System.exit(1); } // grab the file name from the commandline String fileName = args[0]; TestServer.CorbaExporter ce = new TestServer.CorbaExporter(); // get a handle to the remote service to which we want to send the file Context ctx = new InitialContext(); RemoteFileServer stub = (RemoteFileServer) PortableRemoteObject.narrow( ctx.lookup("RemoteFileServer"), RemoteFileServer.class); System.out.println("Sending file " + fileName); // setup the remote input stream. note, the client here is actually // acting as an RMI server (very confusing, i know). this code sets up an // RMI server in the client, which the RemoteFileServer will then // interact with to get the file data.
// Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java // public class SimpleRemoteInputStream extends RemoteInputStreamServer // { // private static final long serialVersionUID = 20080212L; // // /** manages reading from the given stream in a packet-like manner */ // private transient final InputStreamAdapter _inAdapter; // // public SimpleRemoteInputStream(InputStream in) { // this(in, DUMMY_MONITOR, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor) { // this(in, monitor, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor, // int chunkSize) // { // super(in, monitor, chunkSize); // _inAdapter = InputStreamAdapter.create(in, _chunkSize); // } // // @Override // public boolean usingGZIPCompression() // { // // no compression // return false; // } // // @Override // protected int availableImpl() // throws IOException // { // synchronized(getLock()) { // return _in.available(); // } // } // // @Override // protected byte[] readPacket() // throws IOException // { // // will be called synchronized // // // read another packet of data // byte[] packet = _inAdapter.readPacket(); // if(packet != null) { // _monitor.localBytesMoved(this, packet.length); // } // return packet; // } // // @Override // protected long skip(long n) // throws IOException // { // // will be called synchronized // long numSkipped = _in.skip(n); // _monitor.localBytesSkipped(this, numSkipped); // return numSkipped; // } // // } // Path: src/corbaExample/src/java/examples/iiop/TestClient.java import java.io.FileInputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import com.healthmarketscience.rmiio.SimpleRemoteInputStream; /* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iiop; /** * Example corba client which sends a file (given on the command line) to the * example server using a RemoteInputStream. * * @author James Ahlborn */ public class TestClient { public static void main(String[] args) throws Exception { if(args.length < 1) { System.err.println("Usage: <file>"); System.exit(1); } // grab the file name from the commandline String fileName = args[0]; TestServer.CorbaExporter ce = new TestServer.CorbaExporter(); // get a handle to the remote service to which we want to send the file Context ctx = new InitialContext(); RemoteFileServer stub = (RemoteFileServer) PortableRemoteObject.narrow( ctx.lookup("RemoteFileServer"), RemoteFileServer.class); System.out.println("Sending file " + fileName); // setup the remote input stream. note, the client here is actually // acting as an RMI server (very confusing, i know). this code sets up an // RMI server in the client, which the RemoteFileServer will then // interact with to get the file data.
SimpleRemoteInputStream istream = new SimpleRemoteInputStream(
jahlborn/rmiio
src/corbaExample/src/java/examples/iiop/RemoteFileServer.java
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteInputStream.java // public interface RemoteInputStream extends Remote // { // // /** // * Returns <code>true</code> if the stream is using GZIP compression over // * the wire. // * // * @return <code>true</code> iff the stream data is compressed, // * <code>false</code> otherwise // */ // public boolean usingGZIPCompression() // throws IOException, RemoteException; // // /** // * Returns the number of bytes that can be read from this stream without // * blocking. Note that this is an <b>approximate</b> number and should be // * treated as such. // * // * @return the number of bytes that can be read without blocking // */ // public int available() // throws IOException, RemoteException; // // /** // * Closes the input stream and releases the resources for this server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this stream after making this call. // * // * @param readSuccess <code>true</code> iff all data was read successfully // * by the client, <code>false</code> otherwise // */ // public void close(boolean readSuccess) // throws IOException, RemoteException; // // /** // * Reads the next chunk of data for this stream. The amount of data // * returned is up to the underlying implementation. // * // * The given packetId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive a given packet, it may // * reattempt to retrieve the same packet by giving the same packetId as from // * the failed call. However, only the current packet may be reattempted // * (the client cannot attempt to retrieve any other previous packets). When // * requesting a new packet, the caller does not need to give a sequential // * id, just a greater one (hence the term monotonically increasing). // * // * @param packetId client specified id for this packet // * @return iff the packetId was the same one from the last read call, // * returns the last read chunk of data. Otherwise, reads and // * returns a new chunk of data. // */ // public byte[] readPacket(int packetId) // throws IOException, RemoteException; // // /** // * Skips and discards up to the given number of bytes in the stream, and // * returns the actual number of bytes skipped. This method is not allowed // * to be called if using compression on the wire (because of the various // * layers of buffering). // * // * The given skipId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive the return from a skip // * call, it may reattempt the same skip call by giving the same skipId as // * from the failed call. However, only the current skip may be reattempted // * (the client cannot reattempt previous skips). When attempting a new skip // * call, the caller does not need to give a sequential id, just a greater // * one (hence the term monotonically increasing). // * // * @param n the number of bytes to skip // * @param skipId client specified id for this skip attempt // * @return iff the skipId was the same one from the last skip call, returns // * the result of the last skip call. Otherwise, skips up to the // * given number of bytes and returns the actual number of bytes // * skipped. // */ // public long skip(long n, int skipId) // throws IOException, RemoteException; // // }
import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; import com.healthmarketscience.rmiio.RemoteInputStream;
/* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iiop; /** * A simple Remote interface for an RMI server which consumes a * RemoteInputStream. * * @author James Ahlborn */ public interface RemoteFileServer extends Remote {
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteInputStream.java // public interface RemoteInputStream extends Remote // { // // /** // * Returns <code>true</code> if the stream is using GZIP compression over // * the wire. // * // * @return <code>true</code> iff the stream data is compressed, // * <code>false</code> otherwise // */ // public boolean usingGZIPCompression() // throws IOException, RemoteException; // // /** // * Returns the number of bytes that can be read from this stream without // * blocking. Note that this is an <b>approximate</b> number and should be // * treated as such. // * // * @return the number of bytes that can be read without blocking // */ // public int available() // throws IOException, RemoteException; // // /** // * Closes the input stream and releases the resources for this server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this stream after making this call. // * // * @param readSuccess <code>true</code> iff all data was read successfully // * by the client, <code>false</code> otherwise // */ // public void close(boolean readSuccess) // throws IOException, RemoteException; // // /** // * Reads the next chunk of data for this stream. The amount of data // * returned is up to the underlying implementation. // * // * The given packetId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive a given packet, it may // * reattempt to retrieve the same packet by giving the same packetId as from // * the failed call. However, only the current packet may be reattempted // * (the client cannot attempt to retrieve any other previous packets). When // * requesting a new packet, the caller does not need to give a sequential // * id, just a greater one (hence the term monotonically increasing). // * // * @param packetId client specified id for this packet // * @return iff the packetId was the same one from the last read call, // * returns the last read chunk of data. Otherwise, reads and // * returns a new chunk of data. // */ // public byte[] readPacket(int packetId) // throws IOException, RemoteException; // // /** // * Skips and discards up to the given number of bytes in the stream, and // * returns the actual number of bytes skipped. This method is not allowed // * to be called if using compression on the wire (because of the various // * layers of buffering). // * // * The given skipId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive the return from a skip // * call, it may reattempt the same skip call by giving the same skipId as // * from the failed call. However, only the current skip may be reattempted // * (the client cannot reattempt previous skips). When attempting a new skip // * call, the caller does not need to give a sequential id, just a greater // * one (hence the term monotonically increasing). // * // * @param n the number of bytes to skip // * @param skipId client specified id for this skip attempt // * @return iff the skipId was the same one from the last skip call, returns // * the result of the last skip call. Otherwise, skips up to the // * given number of bytes and returns the actual number of bytes // * skipped. // */ // public long skip(long n, int skipId) // throws IOException, RemoteException; // // } // Path: src/corbaExample/src/java/examples/iiop/RemoteFileServer.java import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; import com.healthmarketscience.rmiio.RemoteInputStream; /* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iiop; /** * A simple Remote interface for an RMI server which consumes a * RemoteInputStream. * * @author James Ahlborn */ public interface RemoteFileServer extends Remote {
public void sendFile(RemoteInputStream ristream)
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/util/OutputStreamAdapter.java
// Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // }
import java.io.IOException; import java.io.OutputStream; import com.healthmarketscience.rmiio.PacketOutputStream;
/* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio.util; /** * Utility class for optimizing different write strategies based on the type * of the underlying OutputStream. * * @author James Ahlborn */ public abstract class OutputStreamAdapter { private OutputStreamAdapter() { } /** * @return the underlying OutputStream */ public abstract OutputStream getOutputStream(); /** * Puts the given "packet" into the output stream. The packet should be * filled with data. The caller is giving control of the buffer to the * PacketOutputStream, and therefore should not attempt to use the byte[] * again. * * @param packet fully filled array of bytes to give to the OutputStream */ public abstract void writePacket(byte[] packet) throws IOException; /** * @param istream stream to wrap and for which the implementation is * optimized * @return an OutputStreamAdapter optimized for the stream type */ public static OutputStreamAdapter create( OutputStream istream) {
// Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // } // Path: src/main/java/com/healthmarketscience/rmiio/util/OutputStreamAdapter.java import java.io.IOException; import java.io.OutputStream; import com.healthmarketscience.rmiio.PacketOutputStream; /* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio.util; /** * Utility class for optimizing different write strategies based on the type * of the underlying OutputStream. * * @author James Ahlborn */ public abstract class OutputStreamAdapter { private OutputStreamAdapter() { } /** * @return the underlying OutputStream */ public abstract OutputStream getOutputStream(); /** * Puts the given "packet" into the output stream. The packet should be * filled with data. The caller is giving control of the buffer to the * PacketOutputStream, and therefore should not attempt to use the byte[] * again. * * @param packet fully filled array of bytes to give to the OutputStream */ public abstract void writePacket(byte[] packet) throws IOException; /** * @param istream stream to wrap and for which the implementation is * optimized * @return an OutputStreamAdapter optimized for the stream type */ public static OutputStreamAdapter create( OutputStream istream) {
if(istream instanceof PacketOutputStream) {
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/util/PipeBuffer.java
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // } // // Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // }
import java.io.IOException; import java.nio.BufferUnderflowException; import java.util.ArrayDeque; import java.util.Deque; import com.healthmarketscience.rmiio.PacketInputStream; import com.healthmarketscience.rmiio.PacketOutputStream;
return(_writePosition - _readPosition); } /** @return <code>true</code> if this buffer has as many bytes to read as its capacity, <code>false</code> otherwise */ public boolean isFullToCapacity() { return(readRemaining() == _buf.length); } /** @return <code>true</code> if the buffer has no more space for writing or at least the given packetSize number of bytes, <code>false</code> otherwise */ public boolean isFullPacket(int packetSize) { return(!hasWriteRemaining() || (readRemaining() >= packetSize)); } public void clear() { _readPosition = _writePosition = 0; } } /** * PacketInputStream implementation which reads from a PipeBuffer. One * hiccup here is that the single byte {@link #read()} method may fail if an * attempt is made to read a byte when none are in the PipeBuffer (as this * method is supposed to block in that case and this implementation has no * facility for blocking), so avoid that method call if at all * possible. Note, implementation is not synchronized. */
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // } // // Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // } // Path: src/main/java/com/healthmarketscience/rmiio/util/PipeBuffer.java import java.io.IOException; import java.nio.BufferUnderflowException; import java.util.ArrayDeque; import java.util.Deque; import com.healthmarketscience.rmiio.PacketInputStream; import com.healthmarketscience.rmiio.PacketOutputStream; return(_writePosition - _readPosition); } /** @return <code>true</code> if this buffer has as many bytes to read as its capacity, <code>false</code> otherwise */ public boolean isFullToCapacity() { return(readRemaining() == _buf.length); } /** @return <code>true</code> if the buffer has no more space for writing or at least the given packetSize number of bytes, <code>false</code> otherwise */ public boolean isFullPacket(int packetSize) { return(!hasWriteRemaining() || (readRemaining() >= packetSize)); } public void clear() { _readPosition = _writePosition = 0; } } /** * PacketInputStream implementation which reads from a PipeBuffer. One * hiccup here is that the single byte {@link #read()} method may fail if an * attempt is made to read a byte when none are in the PipeBuffer (as this * method is supposed to block in that case and this implementation has no * facility for blocking), so avoid that method call if at all * possible. Note, implementation is not synchronized. */
public static class InputStreamAdapter extends PacketInputStream
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/util/PipeBuffer.java
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // } // // Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // }
import java.io.IOException; import java.nio.BufferUnderflowException; import java.util.ArrayDeque; import java.util.Deque; import com.healthmarketscience.rmiio.PacketInputStream; import com.healthmarketscience.rmiio.PacketOutputStream;
throws IOException { return _buffer.packetsAvailable(); } @Override public long skip(long n) throws IOException { if(n <= 0) return 0; long toSkip = Math.min(n, _buffer.remaining()); _buffer.skip(toSkip); return toSkip; } /** * @return {@code true} if there will never be anymore bytes to read, * {@code false} otherwise. */ private boolean isFinished() { return(!_buffer.hasRemaining() && _buffer.isWriteClosed()); } } /** * PacketOutputStream implementation which writes to a PipeBuffer. By * default, this class will drop any bytes written after the reader has * closed. Note, implementation is not synchronized. */
// Path: src/main/java/com/healthmarketscience/rmiio/PacketInputStream.java // public abstract class PacketInputStream extends InputStream // { // /** target size of packets returned from packet related methods */ // public static final int DEFAULT_PACKET_SIZE = 1024; // // /** empty packet. useful for returns from partial reads where no data is // currently available, but it's not EOF. */ // protected static final byte[] EMPTY_PACKET = new byte[0]; // // /** the packet size for buffers created in the overflow buffer list */ // private final int _packetSize; // /** whether or not packet reading should accept partial packets by default. // allowing partial packet reads will generally cause more remote calls, but // should reduce latency per-object */ // private final boolean _noDelay; // // public PacketInputStream() { // this(DEFAULT_PACKET_SIZE); // } // // public PacketInputStream(int packetSize) { // this(packetSize, false); // } // // public PacketInputStream(int packetSize, boolean noDelay) { // _packetSize = packetSize; // _noDelay = noDelay; // } // // public int getPacketSize() { // return _packetSize; // } // // public boolean getNoDelay() { // return _noDelay; // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * By default, this method will block until a fully filled packet is created // * (equivalent to calling <code>readPacket(false)</code>). If noDelay is // * enabled, this method will allow partial packet reads (equivalent to // * calling <code>readPacket(true)</code>). // * // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached // */ // public byte[] readPacket() // throws IOException // { // return readPacket(_noDelay); // } // // /** // * Gets the next "packet" from the internal buffer and returns it (if any). // * This method may block until a full packet is read, depending on the value // * of readPartial. // * // * @param readPartial iff <code>false</code>, may block until a full packet // * is read (or EOF), otherwise will return as much data // * as is currently available (which may be 0). // * @return a fully filled array of byte's or <code>null</code> if the end of // * stream has been reached. if no data is available but EOF has not // * been reached, the returned buffer will have length 0. // */ // public abstract byte[] readPacket(boolean readPartial) // throws IOException; // // // /** // * Returns the number of full packets which can be read without blocking. // */ // public abstract int packetsAvailable() // throws IOException; // // // /** // * Reads a packet of data from the given input stream. The given packet is // * filled and returned if possible. If not enough bytes are available, a // * new packet will be created and returned. If the stream is empty, {@code // * null} will be returned. // * // * @param in the InputStream from which to read data // * @param packet the potential output packet (if enough data is available) // * @return a filled packet of data if any available, {@code null} if the // * stream is empty // */ // public static byte[] readPacket(InputStream in, byte[] packet) // throws IOException // { // int readLen = in.read(packet, 0, packet.length); // if(readLen > 0) { // // if(readLen < packet.length) { // // shrink buffer for output // byte[] tmpPacket = new byte[readLen]; // System.arraycopy(packet, 0, tmpPacket, 0, readLen); // packet = tmpPacket; // } // return packet; // // } else if(readLen == 0) { // // return PacketInputStream.EMPTY_PACKET; // } // return null; // } // // } // // Path: src/main/java/com/healthmarketscience/rmiio/PacketOutputStream.java // public abstract class PacketOutputStream extends OutputStream // { // // public PacketOutputStream() { // } // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) // throws IOException; // // } // Path: src/main/java/com/healthmarketscience/rmiio/util/PipeBuffer.java import java.io.IOException; import java.nio.BufferUnderflowException; import java.util.ArrayDeque; import java.util.Deque; import com.healthmarketscience.rmiio.PacketInputStream; import com.healthmarketscience.rmiio.PacketOutputStream; throws IOException { return _buffer.packetsAvailable(); } @Override public long skip(long n) throws IOException { if(n <= 0) return 0; long toSkip = Math.min(n, _buffer.remaining()); _buffer.skip(toSkip); return toSkip; } /** * @return {@code true} if there will never be anymore bytes to read, * {@code false} otherwise. */ private boolean isFinished() { return(!_buffer.hasRemaining() && _buffer.isWriteClosed()); } } /** * PacketOutputStream implementation which writes to a PipeBuffer. By * default, this class will drop any bytes written after the reader has * closed. Note, implementation is not synchronized. */
public static class OutputStreamAdapter extends PacketOutputStream
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/LineIterator.java
// Path: src/main/java/com/healthmarketscience/rmiio/RmiioUtil.java // public static void closeQuietly(Closeable closeable) // { // // yes, this has been written many times before and elsewhere, but i did // // not want to add a dependency just for one method // if(closeable != null) { // try { // closeable.close(); // } catch(IOException e) { // // optionally log the exception, but otherwise ignore // if(LOG.isDebugEnabled()) { // LOG.debug("Failed closing closeable", e); // } // } // } // }
import java.io.BufferedReader; import java.io.IOException; import static com.healthmarketscience.rmiio.RmiioUtil.closeQuietly;
while(true) { _next = _reader.readLine(); if(_next != null) { if (_trimWhitespace) { _next = _next.trim(); } if(_skipBlankLines && _next.length() == 0) { continue; } } return; } } @Override public boolean hasNext() throws IOException { return(_next != null); } @Override protected String nextImpl() throws IOException { String cur = _next; getNext(); return cur; } @Override protected void closeImpl() {
// Path: src/main/java/com/healthmarketscience/rmiio/RmiioUtil.java // public static void closeQuietly(Closeable closeable) // { // // yes, this has been written many times before and elsewhere, but i did // // not want to add a dependency just for one method // if(closeable != null) { // try { // closeable.close(); // } catch(IOException e) { // // optionally log the exception, but otherwise ignore // if(LOG.isDebugEnabled()) { // LOG.debug("Failed closing closeable", e); // } // } // } // } // Path: src/main/java/com/healthmarketscience/rmiio/LineIterator.java import java.io.BufferedReader; import java.io.IOException; import static com.healthmarketscience.rmiio.RmiioUtil.closeQuietly; while(true) { _next = _reader.readLine(); if(_next != null) { if (_trimWhitespace) { _next = _next.trim(); } if(_skipBlankLines && _next.length() == 0) { continue; } } return; } } @Override public boolean hasNext() throws IOException { return(_next != null); } @Override protected String nextImpl() throws IOException { String cur = _next; getNext(); return cur; } @Override protected void closeImpl() {
closeQuietly(_reader);
jahlborn/rmiio
src/test/java/examples/socket/RemoteSocketServer.java
// Path: src/main/java/com/healthmarketscience/rmiio/socket/RMISocket.java // public class RMISocket implements Closeable // { // /** local InputStream for receiving data from local Source which has been // passed to remote system */ // private final PipedInputStream _in; // /** the local source for this socket which must be passed to the remote // system */ // private final Source _source; // /** optional source for the remote system allowing bi-directional // communication */ // private Source _remoteSource; // // public RMISocket() throws IOException { // this(null); // } // // public RMISocket(Source remoteSource) throws IOException { // _in = new PipedInputStream(RemoteInputStreamServer.DEFAULT_CHUNK_SIZE); // PipedOutputStream out = new PipedOutputStream(_in); // _source = new Source(new SimpleRemoteOutputStream(out)); // _remoteSource = remoteSource; // } // // /** // * Returns the InputStream which can be used to read data sent through the // * socket via the local Source which has been passed to the remote system. // */ // public InputStream getInputStream() throws IOException { // return _in; // } // // /** // * Returns the OutputStream of the remote Source, if one has been associated // * with this socket (thus allowing bi-directional communication). // * // * @return the OutputStream for the remote Source // */ // public OutputStream getOutputStream() throws IOException { // if(_remoteSource == null) { // throw new IllegalStateException("no remote source has been associated with this socket"); // } // return _remoteSource.getOutputStream(); // } // // /** // * Returns the local Source for this socket. This must be passed to the // * remote system so that it can send data through this socket. // */ // public Source getSource() { // return _source; // } // // /** // * Closes the local InputStream and the remote Source if one has been // * associated with this socket. // */ // @Override // public void close() throws IOException { // try { // if(_remoteSource != null) { // _remoteSource.close(); // } // } finally { // RmiioUtil.closeQuietly(_in); // } // } // // /** // * Returns the remote Source associated with this socket, if any. This must // * be passed to the remote system in order for this socket to function. // */ // public Source getRemoteSource() { // return _remoteSource; // } // // /** // * Associates a remote Source with this socket, allowing it to be // * bi-directional (at which point the {@link #getOutputStream} method may be // * called). // */ // public void setRemoteSource(Source newRemoteSource) { // _remoteSource = newRemoteSource; // } // // /** // * Serializable stub which must be passed to the remote system in order to // * enable it to send data through this socket. // */ // public static class Source implements Serializable, RemoteClient, Closeable // { // private static final long serialVersionUID = 20120625L; // // /** the handle to the actual remote interface */ // private final RemoteOutputStream _remoteOut; // /** optional client-side RemoteRetry policy */ // private transient RemoteRetry _retry; // /** the actual client-side OutputStream implementation, initialized on // demand by a call to getOutputStream */ // private transient OutputStream _localOut; // /** optional client-side target value for the byte size of the packets of // data sent over the wire */ // private transient Integer _chunkSize; // // private Source(RemoteOutputStream out) { // _remoteOut = out; // } // // public OutputStream getOutputStream() throws IOException { // if(_localOut == null) { // _localOut = RemoteOutputStreamClient.wrap(_remoteOut, _retry, // _chunkSize); // } // return _localOut; // } // // @Override // public void setRemoteRetry(RemoteRetry retry) { // _retry = retry; // } // // /** // * May be called on the client-side in order to set the target chunk size // * used by the underlying implementation. <b>Must</b> be called prior to // * the first call to {@link #getOutputStream}, as once the underlying // * stream is initialized, the chunk size cannot be changed. // * @param chunkSize target value for the byte size of the packets of data // * sent over the wire. note that this is a suggestion, // * actual packet sizes may vary. if <code>null</code>, // * {@link RemoteOutputStreamClient#DEFAULT_CHUNK_SIZE} // * will be used. // */ // public void setChunkSize(Integer chunkSize) { // _chunkSize = chunkSize; // } // // @Override // public void close() throws IOException { // getOutputStream().close(); // } // } // }
import java.io.IOException; import java.rmi.Remote; import com.healthmarketscience.rmiio.socket.RMISocket;
/* Copyright (c) 2012 James Ahlborn 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 examples.socket; /** * A simple Remote interface for an RMI server which enables the creation of a * socket-like connection over RMI. * * @author James Ahlborn */ public interface RemoteSocketServer extends Remote {
// Path: src/main/java/com/healthmarketscience/rmiio/socket/RMISocket.java // public class RMISocket implements Closeable // { // /** local InputStream for receiving data from local Source which has been // passed to remote system */ // private final PipedInputStream _in; // /** the local source for this socket which must be passed to the remote // system */ // private final Source _source; // /** optional source for the remote system allowing bi-directional // communication */ // private Source _remoteSource; // // public RMISocket() throws IOException { // this(null); // } // // public RMISocket(Source remoteSource) throws IOException { // _in = new PipedInputStream(RemoteInputStreamServer.DEFAULT_CHUNK_SIZE); // PipedOutputStream out = new PipedOutputStream(_in); // _source = new Source(new SimpleRemoteOutputStream(out)); // _remoteSource = remoteSource; // } // // /** // * Returns the InputStream which can be used to read data sent through the // * socket via the local Source which has been passed to the remote system. // */ // public InputStream getInputStream() throws IOException { // return _in; // } // // /** // * Returns the OutputStream of the remote Source, if one has been associated // * with this socket (thus allowing bi-directional communication). // * // * @return the OutputStream for the remote Source // */ // public OutputStream getOutputStream() throws IOException { // if(_remoteSource == null) { // throw new IllegalStateException("no remote source has been associated with this socket"); // } // return _remoteSource.getOutputStream(); // } // // /** // * Returns the local Source for this socket. This must be passed to the // * remote system so that it can send data through this socket. // */ // public Source getSource() { // return _source; // } // // /** // * Closes the local InputStream and the remote Source if one has been // * associated with this socket. // */ // @Override // public void close() throws IOException { // try { // if(_remoteSource != null) { // _remoteSource.close(); // } // } finally { // RmiioUtil.closeQuietly(_in); // } // } // // /** // * Returns the remote Source associated with this socket, if any. This must // * be passed to the remote system in order for this socket to function. // */ // public Source getRemoteSource() { // return _remoteSource; // } // // /** // * Associates a remote Source with this socket, allowing it to be // * bi-directional (at which point the {@link #getOutputStream} method may be // * called). // */ // public void setRemoteSource(Source newRemoteSource) { // _remoteSource = newRemoteSource; // } // // /** // * Serializable stub which must be passed to the remote system in order to // * enable it to send data through this socket. // */ // public static class Source implements Serializable, RemoteClient, Closeable // { // private static final long serialVersionUID = 20120625L; // // /** the handle to the actual remote interface */ // private final RemoteOutputStream _remoteOut; // /** optional client-side RemoteRetry policy */ // private transient RemoteRetry _retry; // /** the actual client-side OutputStream implementation, initialized on // demand by a call to getOutputStream */ // private transient OutputStream _localOut; // /** optional client-side target value for the byte size of the packets of // data sent over the wire */ // private transient Integer _chunkSize; // // private Source(RemoteOutputStream out) { // _remoteOut = out; // } // // public OutputStream getOutputStream() throws IOException { // if(_localOut == null) { // _localOut = RemoteOutputStreamClient.wrap(_remoteOut, _retry, // _chunkSize); // } // return _localOut; // } // // @Override // public void setRemoteRetry(RemoteRetry retry) { // _retry = retry; // } // // /** // * May be called on the client-side in order to set the target chunk size // * used by the underlying implementation. <b>Must</b> be called prior to // * the first call to {@link #getOutputStream}, as once the underlying // * stream is initialized, the chunk size cannot be changed. // * @param chunkSize target value for the byte size of the packets of data // * sent over the wire. note that this is a suggestion, // * actual packet sizes may vary. if <code>null</code>, // * {@link RemoteOutputStreamClient#DEFAULT_CHUNK_SIZE} // * will be used. // */ // public void setChunkSize(Integer chunkSize) { // _chunkSize = chunkSize; // } // // @Override // public void close() throws IOException { // getOutputStream().close(); // } // } // } // Path: src/test/java/examples/socket/RemoteSocketServer.java import java.io.IOException; import java.rmi.Remote; import com.healthmarketscience.rmiio.socket.RMISocket; /* Copyright (c) 2012 James Ahlborn 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 examples.socket; /** * A simple Remote interface for an RMI server which enables the creation of a * socket-like connection over RMI. * * @author James Ahlborn */ public interface RemoteSocketServer extends Remote {
public RMISocket.Source connect(RMISocket.Source remoteSource)
jahlborn/rmiio
src/test/java/examples/stream/RemoteFileServer.java
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteInputStream.java // public interface RemoteInputStream extends Remote // { // // /** // * Returns <code>true</code> if the stream is using GZIP compression over // * the wire. // * // * @return <code>true</code> iff the stream data is compressed, // * <code>false</code> otherwise // */ // public boolean usingGZIPCompression() // throws IOException, RemoteException; // // /** // * Returns the number of bytes that can be read from this stream without // * blocking. Note that this is an <b>approximate</b> number and should be // * treated as such. // * // * @return the number of bytes that can be read without blocking // */ // public int available() // throws IOException, RemoteException; // // /** // * Closes the input stream and releases the resources for this server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this stream after making this call. // * // * @param readSuccess <code>true</code> iff all data was read successfully // * by the client, <code>false</code> otherwise // */ // public void close(boolean readSuccess) // throws IOException, RemoteException; // // /** // * Reads the next chunk of data for this stream. The amount of data // * returned is up to the underlying implementation. // * // * The given packetId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive a given packet, it may // * reattempt to retrieve the same packet by giving the same packetId as from // * the failed call. However, only the current packet may be reattempted // * (the client cannot attempt to retrieve any other previous packets). When // * requesting a new packet, the caller does not need to give a sequential // * id, just a greater one (hence the term monotonically increasing). // * // * @param packetId client specified id for this packet // * @return iff the packetId was the same one from the last read call, // * returns the last read chunk of data. Otherwise, reads and // * returns a new chunk of data. // */ // public byte[] readPacket(int packetId) // throws IOException, RemoteException; // // /** // * Skips and discards up to the given number of bytes in the stream, and // * returns the actual number of bytes skipped. This method is not allowed // * to be called if using compression on the wire (because of the various // * layers of buffering). // * // * The given skipId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive the return from a skip // * call, it may reattempt the same skip call by giving the same skipId as // * from the failed call. However, only the current skip may be reattempted // * (the client cannot reattempt previous skips). When attempting a new skip // * call, the caller does not need to give a sequential id, just a greater // * one (hence the term monotonically increasing). // * // * @param n the number of bytes to skip // * @param skipId client specified id for this skip attempt // * @return iff the skipId was the same one from the last skip call, returns // * the result of the last skip call. Otherwise, skips up to the // * given number of bytes and returns the actual number of bytes // * skipped. // */ // public long skip(long n, int skipId) // throws IOException, RemoteException; // // }
import java.io.IOException; import java.rmi.Remote; import com.healthmarketscience.rmiio.RemoteInputStream;
/* Copyright (c) 2007 Health Market Science, Inc. 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 examples.stream; /** * A simple Remote interface for an RMI server which consumes a * RemoteInputStream. * * @author James Ahlborn */ public interface RemoteFileServer extends Remote {
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteInputStream.java // public interface RemoteInputStream extends Remote // { // // /** // * Returns <code>true</code> if the stream is using GZIP compression over // * the wire. // * // * @return <code>true</code> iff the stream data is compressed, // * <code>false</code> otherwise // */ // public boolean usingGZIPCompression() // throws IOException, RemoteException; // // /** // * Returns the number of bytes that can be read from this stream without // * blocking. Note that this is an <b>approximate</b> number and should be // * treated as such. // * // * @return the number of bytes that can be read without blocking // */ // public int available() // throws IOException, RemoteException; // // /** // * Closes the input stream and releases the resources for this server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this stream after making this call. // * // * @param readSuccess <code>true</code> iff all data was read successfully // * by the client, <code>false</code> otherwise // */ // public void close(boolean readSuccess) // throws IOException, RemoteException; // // /** // * Reads the next chunk of data for this stream. The amount of data // * returned is up to the underlying implementation. // * // * The given packetId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive a given packet, it may // * reattempt to retrieve the same packet by giving the same packetId as from // * the failed call. However, only the current packet may be reattempted // * (the client cannot attempt to retrieve any other previous packets). When // * requesting a new packet, the caller does not need to give a sequential // * id, just a greater one (hence the term monotonically increasing). // * // * @param packetId client specified id for this packet // * @return iff the packetId was the same one from the last read call, // * returns the last read chunk of data. Otherwise, reads and // * returns a new chunk of data. // */ // public byte[] readPacket(int packetId) // throws IOException, RemoteException; // // /** // * Skips and discards up to the given number of bytes in the stream, and // * returns the actual number of bytes skipped. This method is not allowed // * to be called if using compression on the wire (because of the various // * layers of buffering). // * // * The given skipId parameter (if used correctly) allows this operation to // * be idempotent. This parameter must be a monotonically increasing, // * positive integer. If the client fails to receive the return from a skip // * call, it may reattempt the same skip call by giving the same skipId as // * from the failed call. However, only the current skip may be reattempted // * (the client cannot reattempt previous skips). When attempting a new skip // * call, the caller does not need to give a sequential id, just a greater // * one (hence the term monotonically increasing). // * // * @param n the number of bytes to skip // * @param skipId client specified id for this skip attempt // * @return iff the skipId was the same one from the last skip call, returns // * the result of the last skip call. Otherwise, skips up to the // * given number of bytes and returns the actual number of bytes // * skipped. // */ // public long skip(long n, int skipId) // throws IOException, RemoteException; // // } // Path: src/test/java/examples/stream/RemoteFileServer.java import java.io.IOException; import java.rmi.Remote; import com.healthmarketscience.rmiio.RemoteInputStream; /* Copyright (c) 2007 Health Market Science, Inc. 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 examples.stream; /** * A simple Remote interface for an RMI server which consumes a * RemoteInputStream. * * @author James Ahlborn */ public interface RemoteFileServer extends Remote {
public void sendFile(RemoteInputStream ristream) throws IOException;
jahlborn/rmiio
src/test/java/examples/stream/TestClient.java
// Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java // public class SimpleRemoteInputStream extends RemoteInputStreamServer // { // private static final long serialVersionUID = 20080212L; // // /** manages reading from the given stream in a packet-like manner */ // private transient final InputStreamAdapter _inAdapter; // // public SimpleRemoteInputStream(InputStream in) { // this(in, DUMMY_MONITOR, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor) { // this(in, monitor, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor, // int chunkSize) // { // super(in, monitor, chunkSize); // _inAdapter = InputStreamAdapter.create(in, _chunkSize); // } // // @Override // public boolean usingGZIPCompression() // { // // no compression // return false; // } // // @Override // protected int availableImpl() // throws IOException // { // synchronized(getLock()) { // return _in.available(); // } // } // // @Override // protected byte[] readPacket() // throws IOException // { // // will be called synchronized // // // read another packet of data // byte[] packet = _inAdapter.readPacket(); // if(packet != null) { // _monitor.localBytesMoved(this, packet.length); // } // return packet; // } // // @Override // protected long skip(long n) // throws IOException // { // // will be called synchronized // long numSkipped = _in.skip(n); // _monitor.localBytesSkipped(this, numSkipped); // return numSkipped; // } // // }
import java.io.FileInputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import com.healthmarketscience.rmiio.SimpleRemoteInputStream;
/* Copyright (c) 2007 Health Market Science, Inc. 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 examples.stream; /** * Example client which sends a file (given on the command line) to the * example server using a RemoteInputStream. * * @author James Ahlborn */ public class TestClient { public static void main(String[] args) throws Exception { if(args.length < 1) { System.err.println("Usage: <file>"); System.exit(1); } // grab the file name from the commandline String fileName = args[0]; // get a handle to the remote service to which we want to send the file Registry registry = LocateRegistry.getRegistry(TestServer.REGISTRY_PORT); RemoteFileServer stub = (RemoteFileServer) registry.lookup("RemoteFileServer"); System.out.println("Sending file " + fileName); // setup the remote input stream. note, the client here is actually // acting as an RMI server (very confusing, i know). this code sets up an // RMI server in the client, which the RemoteFileServer will then // interact with to get the file data.
// Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteInputStream.java // public class SimpleRemoteInputStream extends RemoteInputStreamServer // { // private static final long serialVersionUID = 20080212L; // // /** manages reading from the given stream in a packet-like manner */ // private transient final InputStreamAdapter _inAdapter; // // public SimpleRemoteInputStream(InputStream in) { // this(in, DUMMY_MONITOR, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor) { // this(in, monitor, DEFAULT_CHUNK_SIZE); // } // // public SimpleRemoteInputStream( // InputStream in, // RemoteStreamMonitor<RemoteInputStreamServer> monitor, // int chunkSize) // { // super(in, monitor, chunkSize); // _inAdapter = InputStreamAdapter.create(in, _chunkSize); // } // // @Override // public boolean usingGZIPCompression() // { // // no compression // return false; // } // // @Override // protected int availableImpl() // throws IOException // { // synchronized(getLock()) { // return _in.available(); // } // } // // @Override // protected byte[] readPacket() // throws IOException // { // // will be called synchronized // // // read another packet of data // byte[] packet = _inAdapter.readPacket(); // if(packet != null) { // _monitor.localBytesMoved(this, packet.length); // } // return packet; // } // // @Override // protected long skip(long n) // throws IOException // { // // will be called synchronized // long numSkipped = _in.skip(n); // _monitor.localBytesSkipped(this, numSkipped); // return numSkipped; // } // // } // Path: src/test/java/examples/stream/TestClient.java import java.io.FileInputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import com.healthmarketscience.rmiio.SimpleRemoteInputStream; /* Copyright (c) 2007 Health Market Science, Inc. 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 examples.stream; /** * Example client which sends a file (given on the command line) to the * example server using a RemoteInputStream. * * @author James Ahlborn */ public class TestClient { public static void main(String[] args) throws Exception { if(args.length < 1) { System.err.println("Usage: <file>"); System.exit(1); } // grab the file name from the commandline String fileName = args[0]; // get a handle to the remote service to which we want to send the file Registry registry = LocateRegistry.getRegistry(TestServer.REGISTRY_PORT); RemoteFileServer stub = (RemoteFileServer) registry.lookup("RemoteFileServer"); System.out.println("Sending file " + fileName); // setup the remote input stream. note, the client here is actually // acting as an RMI server (very confusing, i know). this code sets up an // RMI server in the client, which the RemoteFileServer will then // interact with to get the file data.
SimpleRemoteInputStream istream = new SimpleRemoteInputStream(
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/SimpleRemoteOutputStream.java
// Path: src/main/java/com/healthmarketscience/rmiio/util/OutputStreamAdapter.java // public abstract class OutputStreamAdapter // { // // private OutputStreamAdapter() { // } // // /** // * @return the underlying OutputStream // */ // public abstract OutputStream getOutputStream(); // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) throws IOException; // // /** // * @param istream stream to wrap and for which the implementation is // * optimized // * @return an OutputStreamAdapter optimized for the stream type // */ // public static OutputStreamAdapter create( // OutputStream istream) // { // if(istream instanceof PacketOutputStream) { // return new PacketAdapter((PacketOutputStream)istream); // } // return new DefaultAdapter(istream); // } // // /** // * OutputStreamAdapter implementation for PacketOutputStreams. // */ // private static class PacketAdapter extends OutputStreamAdapter // { // private final PacketOutputStream _postream; // // private PacketAdapter(PacketOutputStream postream) { // _postream = postream; // } // // @Override // public PacketOutputStream getOutputStream() { return _postream; } // // @Override // public void writePacket(byte[] packet) throws IOException { // _postream.writePacket(packet); // } // // } // // /** // * OutputStreamAdapter implementation for normal OutputStreams. // */ // private static class DefaultAdapter extends OutputStreamAdapter // { // private final OutputStream _ostream; // // private DefaultAdapter(OutputStream ostream) { // _ostream = ostream; // } // // @Override // public OutputStream getOutputStream() { return _ostream; } // // @Override // public void writePacket(byte[] packet) throws IOException { // _ostream.write(packet, 0, packet.length); // } // // } // // // }
import java.io.IOException; import java.io.OutputStream; import com.healthmarketscience.rmiio.util.OutputStreamAdapter;
/* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio; /** * Concrete implementation of a RemoteOutputStreamServer which expects to * receive uncompressed data, which it will write directly to the underlying * OutputStream. * * @see <a href="{@docRoot}/overview-summary.html#Usage_Notes">Usage Notes</a> * @see #writeReplace * * @author James Ahlborn */ public class SimpleRemoteOutputStream extends RemoteOutputStreamServer { private static final long serialVersionUID = 20080212L; /** manages writing to the given stream in a packet-like manner */
// Path: src/main/java/com/healthmarketscience/rmiio/util/OutputStreamAdapter.java // public abstract class OutputStreamAdapter // { // // private OutputStreamAdapter() { // } // // /** // * @return the underlying OutputStream // */ // public abstract OutputStream getOutputStream(); // // /** // * Puts the given "packet" into the output stream. The packet should be // * filled with data. The caller is giving control of the buffer to the // * PacketOutputStream, and therefore should not attempt to use the byte[] // * again. // * // * @param packet fully filled array of bytes to give to the OutputStream // */ // public abstract void writePacket(byte[] packet) throws IOException; // // /** // * @param istream stream to wrap and for which the implementation is // * optimized // * @return an OutputStreamAdapter optimized for the stream type // */ // public static OutputStreamAdapter create( // OutputStream istream) // { // if(istream instanceof PacketOutputStream) { // return new PacketAdapter((PacketOutputStream)istream); // } // return new DefaultAdapter(istream); // } // // /** // * OutputStreamAdapter implementation for PacketOutputStreams. // */ // private static class PacketAdapter extends OutputStreamAdapter // { // private final PacketOutputStream _postream; // // private PacketAdapter(PacketOutputStream postream) { // _postream = postream; // } // // @Override // public PacketOutputStream getOutputStream() { return _postream; } // // @Override // public void writePacket(byte[] packet) throws IOException { // _postream.writePacket(packet); // } // // } // // /** // * OutputStreamAdapter implementation for normal OutputStreams. // */ // private static class DefaultAdapter extends OutputStreamAdapter // { // private final OutputStream _ostream; // // private DefaultAdapter(OutputStream ostream) { // _ostream = ostream; // } // // @Override // public OutputStream getOutputStream() { return _ostream; } // // @Override // public void writePacket(byte[] packet) throws IOException { // _ostream.write(packet, 0, packet.length); // } // // } // // // } // Path: src/main/java/com/healthmarketscience/rmiio/SimpleRemoteOutputStream.java import java.io.IOException; import java.io.OutputStream; import com.healthmarketscience.rmiio.util.OutputStreamAdapter; /* Copyright (c) 2007 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.rmiio; /** * Concrete implementation of a RemoteOutputStreamServer which expects to * receive uncompressed data, which it will write directly to the underlying * OutputStream. * * @see <a href="{@docRoot}/overview-summary.html#Usage_Notes">Usage Notes</a> * @see #writeReplace * * @author James Ahlborn */ public class SimpleRemoteOutputStream extends RemoteOutputStreamServer { private static final long serialVersionUID = 20080212L; /** manages writing to the given stream in a packet-like manner */
private transient final OutputStreamAdapter _outAdapter;
jahlborn/rmiio
src/test/java/examples/iterator/TestServer.java
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteIterator.java // public interface RemoteIterator<DataType> // extends CloseableIOIterator<DataType>, Serializable, RemoteClient // { // // /** // * Closes the iterator and releases the resources for the server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this iterator after making this call. // */ // @Override // public void close() throws IOException; // // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import com.healthmarketscience.rmiio.RemoteIterator;
/* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iterator; /** * Example server which consumes a bunch of strings using a RemoteIterator * (and sticks them in a local temp file). * * @author James Ahlborn */ public class TestServer { public static final int REGISTRY_PORT = Registry.REGISTRY_PORT; public static class StringServer implements RemoteStringServer {
// Path: src/main/java/com/healthmarketscience/rmiio/RemoteIterator.java // public interface RemoteIterator<DataType> // extends CloseableIOIterator<DataType>, Serializable, RemoteClient // { // // /** // * Closes the iterator and releases the resources for the server // * object. Note that the remote object <i>may no longer be accessible</i> // * after this call (depending on the implementation), so clients should not // * attempt to use this iterator after making this call. // */ // @Override // public void close() throws IOException; // // } // Path: src/test/java/examples/iterator/TestServer.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import com.healthmarketscience.rmiio.RemoteIterator; /* Copyright (c) 2007 Health Market Science, Inc. 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 examples.iterator; /** * Example server which consumes a bunch of strings using a RemoteIterator * (and sticks them in a local temp file). * * @author James Ahlborn */ public class TestServer { public static final int REGISTRY_PORT = Registry.REGISTRY_PORT; public static class StringServer implements RemoteStringServer {
public void sendStrings(RemoteIterator<String> iter) throws IOException {
cathive/fx-inject
fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/converter/ImageConverter.java // @Converter // public class ImageConverter implements AttributeConverter<Image, byte[]> { // // /** Logger for this instance. */ // private static final Logger LOGGER = Logger.getLogger(ImageConverter.class.getName()); // // @Override // public byte[] convertToDatabaseColumn(final Image image) { // byte[] bytes; // try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024)) { // ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); // bytes = baos.toByteArray(); // } catch (final IOException e) { // LOGGER.log(Level.WARNING, "Couldn't convert image to byte array"); // bytes = null; // } // return bytes; // } // // @Override // public Image convertToEntityAttribute(final byte[] bytes) { // Image img; // try (final ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) { // img = new Image(bis); // } catch (final IOException e) { // LOGGER.log(Level.WARNING, "Couldn't create image from byte array."); // img = null; // } // return img; // } // // }
import com.cathive.fx.apps.contacts.model.converter.ImageConverter; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image; import javax.persistence.*; import java.io.Serializable;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts.model; /** * @author Benjamin P. Jung */ @Entity @Table(name = "contact") @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) @DiscriminatorValue(value = "?") @Inheritance(strategy=InheritanceType.JOINED) public abstract class Contact extends AbstractEntity implements Serializable { /** @see java.io.Serializable */ private static final long serialVersionUID = 1L; // <editor-fold desc="Property: photo"> public static final String PHOTO_PROPERTY = "photo"; private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); public ObjectProperty<Image> photoProperty() { return this.photo; } @Column(name = "photo_data")
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/converter/ImageConverter.java // @Converter // public class ImageConverter implements AttributeConverter<Image, byte[]> { // // /** Logger for this instance. */ // private static final Logger LOGGER = Logger.getLogger(ImageConverter.class.getName()); // // @Override // public byte[] convertToDatabaseColumn(final Image image) { // byte[] bytes; // try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024)) { // ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos); // bytes = baos.toByteArray(); // } catch (final IOException e) { // LOGGER.log(Level.WARNING, "Couldn't convert image to byte array"); // bytes = null; // } // return bytes; // } // // @Override // public Image convertToEntityAttribute(final byte[] bytes) { // Image img; // try (final ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) { // img = new Image(bis); // } catch (final IOException e) { // LOGGER.log(Level.WARNING, "Couldn't create image from byte array."); // img = null; // } // return img; // } // // } // Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java import com.cathive.fx.apps.contacts.model.converter.ImageConverter; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image; import javax.persistence.*; import java.io.Serializable; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts.model; /** * @author Benjamin P. Jung */ @Entity @Table(name = "contact") @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) @DiscriminatorValue(value = "?") @Inheritance(strategy=InheritanceType.JOINED) public abstract class Contact extends AbstractEntity implements Serializable { /** @see java.io.Serializable */ private static final long serialVersionUID = 1L; // <editor-fold desc="Property: photo"> public static final String PHOTO_PROPERTY = "photo"; private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); public ObjectProperty<Image> photoProperty() { return this.photo; } @Column(name = "photo_data")
@Convert(converter = ImageConverter.class)
cathive/fx-inject
fx-cdi/src/main/java/com/cathive/fx/cdi/CdiFXMLLoaderFactory.java
// Path: fx-cdi/src/main/java/com/cathive/fx/cdi/CdiFXMLLoader.java // class CdiFXMLLoader extends FXMLLoader { // // // Some marker strings for unspecified values. // public static final String LOCATION_UNSPECIFIED = "$$$LOCATION_UNSPECIFIED$$$"; // public static final String RESOURCES_UNSPECIFIED = "$$$RESOURCES_UNSPECIFIED$$$"; // public static final String CHARSET_UNSPECIFIED = "$$$CHARSET_UNSPECIFIED$$$"; // // /** // * A reference to all the package names that won't work as supposed to when trying // * to instantiate beans from within via CDI in conjunction with FXML builders. // * <p>This will avoid an exception message caused by a {@link com.sun.javafx.fxml.PropertyNotFoundException} // * <em>'Property "${propertyName}" does not exist or is read-only'</em>.</p> // * @see com.sun.javafx.fxml.PropertyNotFoundException // */ // private static final String[] CDI_BLACKLIST = new String[] { // "javafx", // "java.awt", // "javax.swing" // }; // // /** A default (non-CDI aware) JavaFX builder factory. */ // private final JavaFXBuilderFactory defaultBuilderFactory; // // /** // * Default constructor. // */ // CdiFXMLLoader() { // // super(); // // // Uses the currently loaded CDI implementation to look up controller classes // // that have been specified via "fx:controller='...'" in our FXML files. // this.setControllerFactory((aClass) -> CDI.current().select(aClass)); // // // Initializes the default JavaFX builder factory to be used for non CDI-aware beans. // this.defaultBuilderFactory = new JavaFXBuilderFactory(); // // this.setBuilderFactory((aClass) -> { // // // Uses the default builder factory to retrieve builders where applicable. // final Builder<?> defaultBuilder = defaultBuilderFactory.getBuilder(aClass); // if (defaultBuilder != null) { // return defaultBuilder; // } // // // Make sure that we use a "null" builder for components that are 'blacklisted'. // final String packageName = aClass.getPackage().getName(); // for (final String blacklisted : CDI_BLACKLIST) { // if (packageName.startsWith(blacklisted)) { // return null; // } // } // // return new CdiFXMLComponentBuilder(aClass); // // }); // // } // // @Override // public String toString() { // return String.format("[CDI-aware] %s", super.toString()); // } // // }
import com.cathive.fx.inject.core.FXMLLoaderParams; import javafx.fxml.FXMLLoader; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.InjectionPoint; import java.net.URL; import java.nio.charset.Charset; import java.util.ResourceBundle; import static com.cathive.fx.cdi.CdiFXMLLoader.*;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.cdi; /** * This factory is responsible for the production of CDI-aware {@link javafx.fxml.FXMLLoader} instances. * * @author Benjamin P. Jung */ @ApplicationScoped class CdiFXMLLoaderFactory { /** * Create a CDI-aware FXMLLoader. * If an annotation of type @FXMLLoaderParams can be found, use it's parameters * to configure the FXMLLoader instance that shall be used to perform the loading * of the FXML file. * * @param injectionPoint * Injection point. * @return * A new FXMLLoader instance. */ @Produces @FXMLLoaderParams FXMLLoader createCdiFXMLLoader(final InjectionPoint injectionPoint) {
// Path: fx-cdi/src/main/java/com/cathive/fx/cdi/CdiFXMLLoader.java // class CdiFXMLLoader extends FXMLLoader { // // // Some marker strings for unspecified values. // public static final String LOCATION_UNSPECIFIED = "$$$LOCATION_UNSPECIFIED$$$"; // public static final String RESOURCES_UNSPECIFIED = "$$$RESOURCES_UNSPECIFIED$$$"; // public static final String CHARSET_UNSPECIFIED = "$$$CHARSET_UNSPECIFIED$$$"; // // /** // * A reference to all the package names that won't work as supposed to when trying // * to instantiate beans from within via CDI in conjunction with FXML builders. // * <p>This will avoid an exception message caused by a {@link com.sun.javafx.fxml.PropertyNotFoundException} // * <em>'Property "${propertyName}" does not exist or is read-only'</em>.</p> // * @see com.sun.javafx.fxml.PropertyNotFoundException // */ // private static final String[] CDI_BLACKLIST = new String[] { // "javafx", // "java.awt", // "javax.swing" // }; // // /** A default (non-CDI aware) JavaFX builder factory. */ // private final JavaFXBuilderFactory defaultBuilderFactory; // // /** // * Default constructor. // */ // CdiFXMLLoader() { // // super(); // // // Uses the currently loaded CDI implementation to look up controller classes // // that have been specified via "fx:controller='...'" in our FXML files. // this.setControllerFactory((aClass) -> CDI.current().select(aClass)); // // // Initializes the default JavaFX builder factory to be used for non CDI-aware beans. // this.defaultBuilderFactory = new JavaFXBuilderFactory(); // // this.setBuilderFactory((aClass) -> { // // // Uses the default builder factory to retrieve builders where applicable. // final Builder<?> defaultBuilder = defaultBuilderFactory.getBuilder(aClass); // if (defaultBuilder != null) { // return defaultBuilder; // } // // // Make sure that we use a "null" builder for components that are 'blacklisted'. // final String packageName = aClass.getPackage().getName(); // for (final String blacklisted : CDI_BLACKLIST) { // if (packageName.startsWith(blacklisted)) { // return null; // } // } // // return new CdiFXMLComponentBuilder(aClass); // // }); // // } // // @Override // public String toString() { // return String.format("[CDI-aware] %s", super.toString()); // } // // } // Path: fx-cdi/src/main/java/com/cathive/fx/cdi/CdiFXMLLoaderFactory.java import com.cathive.fx.inject.core.FXMLLoaderParams; import javafx.fxml.FXMLLoader; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.InjectionPoint; import java.net.URL; import java.nio.charset.Charset; import java.util.ResourceBundle; import static com.cathive.fx.cdi.CdiFXMLLoader.*; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.cdi; /** * This factory is responsible for the production of CDI-aware {@link javafx.fxml.FXMLLoader} instances. * * @author Benjamin P. Jung */ @ApplicationScoped class CdiFXMLLoaderFactory { /** * Create a CDI-aware FXMLLoader. * If an annotation of type @FXMLLoaderParams can be found, use it's parameters * to configure the FXMLLoader instance that shall be used to perform the loading * of the FXML file. * * @param injectionPoint * Injection point. * @return * A new FXMLLoader instance. */ @Produces @FXMLLoaderParams FXMLLoader createCdiFXMLLoader(final InjectionPoint injectionPoint) {
final CdiFXMLLoader fxmlLoader = new CdiFXMLLoader();
cathive/fx-inject
fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Person.java
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/converter/SexConverter.java // @Converter // public class SexConverter implements AttributeConverter<Sex, Integer> { // // @Override // public Integer convertToDatabaseColumn(final Sex attribute) { // return attribute == null ? Sex.NOT_KNOWN.getValue() : Integer.valueOf(attribute.getValue()); // } // // @Override // public Sex convertToEntityAttribute(final Integer dbData) { // return dbData == null ? Sex.NOT_KNOWN : Sex.valueOf(dbData.intValue()); // } // // }
import com.cathive.fx.apps.contacts.model.converter.SexConverter; import javafx.beans.NamedArg; import javafx.beans.binding.Bindings; import javafx.beans.property.*; import javax.persistence.*; import java.io.Serializable; import static javafx.beans.binding.Bindings.createObjectBinding; import static javafx.beans.binding.Bindings.createStringBinding;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts.model; /** * Encapsulates a person entity. * * @author Benjamin P. Jung */ @Entity @Table(name = "contact_person") @DiscriminatorValue(value = "P") public class Person extends Contact implements Serializable { /** @see java.io.Serializable */ private static final long serialVersionUid = 1L; public Person() { super(); } public Person(@NamedArg(FIRST_NAME_PROPERTY) final String firstName, @NamedArg(LAST_NAME_PROPERTY) final String lastName) { this(); this.setFirstName(firstName); this.setLastName(lastName); } @Override public ContactType getType() { return ContactType.PERSON; } // <editor-fold desc="Property: last name"> public static final String LAST_NAME_PROPERTY = "lastName"; private final StringProperty lastName = new SimpleStringProperty(this, LAST_NAME_PROPERTY); public StringProperty lastNameProperty() { return this.lastName; } @Column(name = "last_name") public String getLastName() { return this.lastName.get(); } public void setLastName(final String lastName) { this.lastName.set(lastName); } // </editor-fold> // <editor-fold desc="Property: first name"> public static final String FIRST_NAME_PROPERTY = "firstName"; private final StringProperty firstName = new SimpleStringProperty(this, FIRST_NAME_PROPERTY); @Column(name = "first_name") public String getFirstName() { return this.firstName.get(); } public void setFirstName(final String firstName) { this.firstName.set(firstName); } public StringProperty firstNameProperty() { return this.firstName; } // </editor-fold> // <editor-fold desc="Property: sex"> public static final String SEX_PROPERTY = "sex"; private final ObjectProperty<Sex> sex = new SimpleObjectProperty<>(this, SEX_PROPERTY, Sex.NOT_KNOWN); @Column(name = "sex")
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/converter/SexConverter.java // @Converter // public class SexConverter implements AttributeConverter<Sex, Integer> { // // @Override // public Integer convertToDatabaseColumn(final Sex attribute) { // return attribute == null ? Sex.NOT_KNOWN.getValue() : Integer.valueOf(attribute.getValue()); // } // // @Override // public Sex convertToEntityAttribute(final Integer dbData) { // return dbData == null ? Sex.NOT_KNOWN : Sex.valueOf(dbData.intValue()); // } // // } // Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Person.java import com.cathive.fx.apps.contacts.model.converter.SexConverter; import javafx.beans.NamedArg; import javafx.beans.binding.Bindings; import javafx.beans.property.*; import javax.persistence.*; import java.io.Serializable; import static javafx.beans.binding.Bindings.createObjectBinding; import static javafx.beans.binding.Bindings.createStringBinding; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts.model; /** * Encapsulates a person entity. * * @author Benjamin P. Jung */ @Entity @Table(name = "contact_person") @DiscriminatorValue(value = "P") public class Person extends Contact implements Serializable { /** @see java.io.Serializable */ private static final long serialVersionUid = 1L; public Person() { super(); } public Person(@NamedArg(FIRST_NAME_PROPERTY) final String firstName, @NamedArg(LAST_NAME_PROPERTY) final String lastName) { this(); this.setFirstName(firstName); this.setLastName(lastName); } @Override public ContactType getType() { return ContactType.PERSON; } // <editor-fold desc="Property: last name"> public static final String LAST_NAME_PROPERTY = "lastName"; private final StringProperty lastName = new SimpleStringProperty(this, LAST_NAME_PROPERTY); public StringProperty lastNameProperty() { return this.lastName; } @Column(name = "last_name") public String getLastName() { return this.lastName.get(); } public void setLastName(final String lastName) { this.lastName.set(lastName); } // </editor-fold> // <editor-fold desc="Property: first name"> public static final String FIRST_NAME_PROPERTY = "firstName"; private final StringProperty firstName = new SimpleStringProperty(this, FIRST_NAME_PROPERTY); @Column(name = "first_name") public String getFirstName() { return this.firstName.get(); } public void setFirstName(final String firstName) { this.firstName.set(firstName); } public StringProperty firstNameProperty() { return this.firstName; } // </editor-fold> // <editor-fold desc="Property: sex"> public static final String SEX_PROPERTY = "sex"; private final ObjectProperty<Sex> sex = new SimpleObjectProperty<>(this, SEX_PROPERTY, Sex.NOT_KNOWN); @Column(name = "sex")
@Convert(converter = SexConverter.class)
cathive/fx-inject
fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactsApp.java
// Path: fx-cdi/src/main/java/com/cathive/fx/cdi/CdiApplication.java // public abstract class CdiApplication extends Application { // // /** CDI loader to be used during application initialization. */ // private CDILoader fxCdiLoader; // // /** // * Default constructor. // * Creates a new CDI-aware JavaFX application instance. // */ // public CdiApplication() { // // super(); // // // Sets the JavaFX application instance to be used when injecting an instance of this class. // JavaFXExtension.setJavaFxApplication(this); // // // Searches for a FxCdiLoader instance. // final ServiceLoader<CDILoader> serviceLoader = ServiceLoader.load(CDILoader.class); // final Iterator<CDILoader> loaderIterator = serviceLoader.iterator(); // if (!loaderIterator.hasNext()) { // throw new IllegalStateException("No CDI Loader implementation for JavaFX could be found on your classpath."); // } // final CDILoader loader = loaderIterator.next(); // if (loaderIterator.hasNext()) { // throw new IllegalStateException("More than one CDI Loader implementation for JavaFX could be found on your classpath."); // } // this.fxCdiLoader = loader; // // } // // @Override // public void init() throws Exception { // super.init(); // this.fxCdiLoader.initialize(); // } // // @Override // public void stop() throws Exception { // this.fxCdiLoader.shutdown(); // JavaFXExtension.setJavaFxApplication(null); // super.stop(); // } // // @Override // public String toString() { // return String.format("[CDI-aware] %s", super.toString()); // } // // }
import com.cathive.fx.cdi.CdiApplication; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import java.util.ResourceBundle;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * Contacts app * @author Benjamin P. Jung */ @Named("app") @ApplicationScoped
// Path: fx-cdi/src/main/java/com/cathive/fx/cdi/CdiApplication.java // public abstract class CdiApplication extends Application { // // /** CDI loader to be used during application initialization. */ // private CDILoader fxCdiLoader; // // /** // * Default constructor. // * Creates a new CDI-aware JavaFX application instance. // */ // public CdiApplication() { // // super(); // // // Sets the JavaFX application instance to be used when injecting an instance of this class. // JavaFXExtension.setJavaFxApplication(this); // // // Searches for a FxCdiLoader instance. // final ServiceLoader<CDILoader> serviceLoader = ServiceLoader.load(CDILoader.class); // final Iterator<CDILoader> loaderIterator = serviceLoader.iterator(); // if (!loaderIterator.hasNext()) { // throw new IllegalStateException("No CDI Loader implementation for JavaFX could be found on your classpath."); // } // final CDILoader loader = loaderIterator.next(); // if (loaderIterator.hasNext()) { // throw new IllegalStateException("More than one CDI Loader implementation for JavaFX could be found on your classpath."); // } // this.fxCdiLoader = loader; // // } // // @Override // public void init() throws Exception { // super.init(); // this.fxCdiLoader.initialize(); // } // // @Override // public void stop() throws Exception { // this.fxCdiLoader.shutdown(); // JavaFXExtension.setJavaFxApplication(null); // super.stop(); // } // // @Override // public String toString() { // return String.format("[CDI-aware] %s", super.toString()); // } // // } // Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactsApp.java import com.cathive.fx.cdi.CdiApplication; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import java.util.ResourceBundle; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * Contacts app * @author Benjamin P. Jung */ @Named("app") @ApplicationScoped
public class ContactsApp extends CdiApplication {
cathive/fx-inject
fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactDetailsPane.java
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java // @Entity // @Table(name = "contact") // @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) // @DiscriminatorValue(value = "?") // @Inheritance(strategy=InheritanceType.JOINED) // public abstract class Contact extends AbstractEntity // implements Serializable { // // /** @see java.io.Serializable */ // private static final long serialVersionUID = 1L; // // // <editor-fold desc="Property: photo"> // public static final String PHOTO_PROPERTY = "photo"; // private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); // public ObjectProperty<Image> photoProperty() { // return this.photo; // } // @Column(name = "photo_data") // @Convert(converter = ImageConverter.class) // public Image getPhoto() { // return this.photo.get(); // } // public void setPhoto(final Image photo) { // this.photo.set(photo); // } // // </editor-fold> // // // public Contact() { // super(); // } // // // @Transient // public abstract ContactType getType(); // // public static <T extends Contact> T create(final Class<T> contactType) { // final T contact; // try { // contact = contactType.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // return contact; // } // // }
import javax.inject.Inject; import javax.inject.Named; import com.cathive.fx.apps.contacts.model.Contact; import com.cathive.fx.inject.core.FXMLComponent; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * @author Benjamin P. Jung */ @Named @FXMLComponent(location = "ContactDetailsPane.fxml", resources = "com.cathive.fx.apps.contacts.Messages") public class ContactDetailsPane extends VBox { @Inject private Instance<ContactsApp> appInstance; @Inject private ContactRendererFactory displayNameRenderers; @FXML private Label displayNameLabel; @FXML private Label firstNameLabel; @FXML private Label lastNameLabel; @FXML private ImageView photoImageView; // <editor-fold desc="Property: read only"> public static final String READ_ONLY_PROPERTY = "readOnly"; private final BooleanProperty readOnly = new SimpleBooleanProperty(this, READ_ONLY_PROPERTY); public boolean isReadOnly() { return this.readOnly.get(); } public void setReadOnly(final boolean readOnly) { this.readOnly.set(readOnly); } public BooleanProperty readOnlyBooleanProperty() { return this.readOnly; } // </editor-fold> /** Contact to be displayed by this component (thus: the "model"). */
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java // @Entity // @Table(name = "contact") // @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) // @DiscriminatorValue(value = "?") // @Inheritance(strategy=InheritanceType.JOINED) // public abstract class Contact extends AbstractEntity // implements Serializable { // // /** @see java.io.Serializable */ // private static final long serialVersionUID = 1L; // // // <editor-fold desc="Property: photo"> // public static final String PHOTO_PROPERTY = "photo"; // private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); // public ObjectProperty<Image> photoProperty() { // return this.photo; // } // @Column(name = "photo_data") // @Convert(converter = ImageConverter.class) // public Image getPhoto() { // return this.photo.get(); // } // public void setPhoto(final Image photo) { // this.photo.set(photo); // } // // </editor-fold> // // // public Contact() { // super(); // } // // // @Transient // public abstract ContactType getType(); // // public static <T extends Contact> T create(final Class<T> contactType) { // final T contact; // try { // contact = contactType.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // return contact; // } // // } // Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactDetailsPane.java import javax.inject.Inject; import javax.inject.Named; import com.cathive.fx.apps.contacts.model.Contact; import com.cathive.fx.inject.core.FXMLComponent; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * @author Benjamin P. Jung */ @Named @FXMLComponent(location = "ContactDetailsPane.fxml", resources = "com.cathive.fx.apps.contacts.Messages") public class ContactDetailsPane extends VBox { @Inject private Instance<ContactsApp> appInstance; @Inject private ContactRendererFactory displayNameRenderers; @FXML private Label displayNameLabel; @FXML private Label firstNameLabel; @FXML private Label lastNameLabel; @FXML private ImageView photoImageView; // <editor-fold desc="Property: read only"> public static final String READ_ONLY_PROPERTY = "readOnly"; private final BooleanProperty readOnly = new SimpleBooleanProperty(this, READ_ONLY_PROPERTY); public boolean isReadOnly() { return this.readOnly.get(); } public void setReadOnly(final boolean readOnly) { this.readOnly.set(readOnly); } public BooleanProperty readOnlyBooleanProperty() { return this.readOnly; } // </editor-fold> /** Contact to be displayed by this component (thus: the "model"). */
private final ObjectProperty<Contact> contact = new SimpleObjectProperty<>(this, "contact");
cathive/fx-inject
fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactListCell.java
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java // @Entity // @Table(name = "contact") // @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) // @DiscriminatorValue(value = "?") // @Inheritance(strategy=InheritanceType.JOINED) // public abstract class Contact extends AbstractEntity // implements Serializable { // // /** @see java.io.Serializable */ // private static final long serialVersionUID = 1L; // // // <editor-fold desc="Property: photo"> // public static final String PHOTO_PROPERTY = "photo"; // private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); // public ObjectProperty<Image> photoProperty() { // return this.photo; // } // @Column(name = "photo_data") // @Convert(converter = ImageConverter.class) // public Image getPhoto() { // return this.photo.get(); // } // public void setPhoto(final Image photo) { // this.photo.set(photo); // } // // </editor-fold> // // // public Contact() { // super(); // } // // // @Transient // public abstract ContactType getType(); // // public static <T extends Contact> T create(final Class<T> contactType) { // final T contact; // try { // contact = contactType.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // return contact; // } // // }
import com.cathive.fx.apps.contacts.model.Contact; import com.cathive.fx.inject.core.FXMLComponent; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named;
/* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * List cell to display contacts. * @author Benjamin P. Jung */ @Named @Dependent @FXMLComponent(location = "ContactListCell.fxml") public class ContactListCell extends HBox { public static final String CONTACT_PROPERTY = "contact";
// Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/model/Contact.java // @Entity // @Table(name = "contact") // @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR) // @DiscriminatorValue(value = "?") // @Inheritance(strategy=InheritanceType.JOINED) // public abstract class Contact extends AbstractEntity // implements Serializable { // // /** @see java.io.Serializable */ // private static final long serialVersionUID = 1L; // // // <editor-fold desc="Property: photo"> // public static final String PHOTO_PROPERTY = "photo"; // private final ObjectProperty<Image> photo = new SimpleObjectProperty<>(this, PHOTO_PROPERTY); // public ObjectProperty<Image> photoProperty() { // return this.photo; // } // @Column(name = "photo_data") // @Convert(converter = ImageConverter.class) // public Image getPhoto() { // return this.photo.get(); // } // public void setPhoto(final Image photo) { // this.photo.set(photo); // } // // </editor-fold> // // // public Contact() { // super(); // } // // // @Transient // public abstract ContactType getType(); // // public static <T extends Contact> T create(final Class<T> contactType) { // final T contact; // try { // contact = contactType.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new IllegalStateException(e); // } // return contact; // } // // } // Path: fx-inject-examples/addressbook-app/src/main/java/com/cathive/fx/apps/contacts/ContactListCell.java import com.cathive.fx.apps.contacts.model.Contact; import com.cathive.fx.inject.core.FXMLComponent; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; /* * Copyright (C) 2013,2014 The Cat Hive Developers. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cathive.fx.apps.contacts; /** * List cell to display contacts. * @author Benjamin P. Jung */ @Named @Dependent @FXMLComponent(location = "ContactListCell.fxml") public class ContactListCell extends HBox { public static final String CONTACT_PROPERTY = "contact";
private final ObjectProperty<Contact> contact = new SimpleObjectProperty<>(this, CONTACT_PROPERTY);
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/DeserializedDifference.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // }
import java.util.Collections; import java.util.HashSet; import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer;
package eu.mais_h.mathsync; class DeserializedDifference<T> implements Difference<T> { private final Set<T> added; private final Set<T> removed;
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // Path: java/core/src/main/java/eu/mais_h/mathsync/DeserializedDifference.java import java.util.Collections; import java.util.HashSet; import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer; package eu.mais_h.mathsync; class DeserializedDifference<T> implements Difference<T> { private final Set<T> added; private final Set<T> removed;
DeserializedDifference(Difference<byte[]> serialized, Deserializer<T> deserializer) {
3musket33rs/mathsync
java/core/src/test/java/eu/mais_h/mathsync/SummarizerFromJsonTest.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import java.util.Arrays; import java.util.Set; import org.junit.Test; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync; public class SummarizerFromJsonTest { private Digester digester = Sha1Digester.get(); private BucketSelector selector = Defaults.defaultSelector(); private byte[] item1 = new byte[] { 1, 2 }; private byte[] item2 = new byte[] { 2, 2 }; private byte[] item3 = new byte[] { 3, 2 }; @Test public void test_should_generate_summary_from_IBF() { final Summary ibf = new Ibf(32, digester, selector).plus(item1).plus(item2).plus(item3);
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: java/core/src/test/java/eu/mais_h/mathsync/SummarizerFromJsonTest.java import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import java.util.Arrays; import java.util.Set; import org.junit.Test; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync; public class SummarizerFromJsonTest { private Digester digester = Sha1Digester.get(); private BucketSelector selector = Defaults.defaultSelector(); private byte[] item1 = new byte[] { 1, 2 }; private byte[] item2 = new byte[] { 2, 2 }; private byte[] item3 = new byte[] { 3, 2 }; @Test public void test_should_generate_summary_from_IBF() { final Summary ibf = new Ibf(32, digester, selector).plus(item1).plus(item2).plus(item3);
Summarizer throughJson = SummarizerFromJson.custom(new Function<Integer, String>() {
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromJson.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync; /** * Summarizer which deserializes JSON payloads from a remote source. */ public class SummarizerFromJson implements Summarizer { private final Function<Integer, String> producer;
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromJson.java import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync; /** * Summarizer which deserializes JSON payloads from a remote source. */ public class SummarizerFromJson implements Summarizer { private final Function<Integer, String> producer;
private final Digester digester;
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromJson.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync; /** * Summarizer which deserializes JSON payloads from a remote source. */ public class SummarizerFromJson implements Summarizer { private final Function<Integer, String> producer; private final Digester digester; private final BucketSelector selector; SummarizerFromJson(Function<Integer, String> producer, Digester digester, BucketSelector selector) { this.producer = producer; this.digester = digester; this.selector = selector; } @Override public Summary summarize(int level) { String json = producer.apply(level); JSONTokener tokener = new JSONTokener(json); char first = tokener.nextClean(); tokener.back(); if (first == '{') { return new FullContent(tokener); } else if (first == '[') { return new Ibf(tokener, digester, selector); } else { throw new IllegalStateException("JSON " + json + " is neither detected as an array nor as a hash, cannot be parsed"); } } /** * Builds a simple summarizer. * * @param producer function which fetches the JSON payload corresponding to a given level. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default bucket selector. */ public static <T> Summarizer simple(Function<Integer, String> producer) {
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromJson.java import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync; /** * Summarizer which deserializes JSON payloads from a remote source. */ public class SummarizerFromJson implements Summarizer { private final Function<Integer, String> producer; private final Digester digester; private final BucketSelector selector; SummarizerFromJson(Function<Integer, String> producer, Digester digester, BucketSelector selector) { this.producer = producer; this.digester = digester; this.selector = selector; } @Override public Summary summarize(int level) { String json = producer.apply(level); JSONTokener tokener = new JSONTokener(json); char first = tokener.nextClean(); tokener.back(); if (first == '{') { return new FullContent(tokener); } else if (first == '[') { return new Ibf(tokener, digester, selector); } else { throw new IllegalStateException("JSON " + json + " is neither detected as an array nor as a hash, cannot be parsed"); } } /** * Builds a simple summarizer. * * @param producer function which fetches the JSON payload corresponding to a given level. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default bucket selector. */ public static <T> Summarizer simple(Function<Integer, String> producer) {
return custom(producer, Sha1Digester.get(), Defaults.defaultSelector());
3musket33rs/mathsync
integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
private final Summarizer summarizer = SummarizerFromItems.simple(content.entrySet(), StringSerializer.create(new Function<Entry<String, String>, String>() {
3musket33rs/mathsync
integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
private final Summarizer summarizer = SummarizerFromItems.simple(content.entrySet(), StringSerializer.create(new Function<Entry<String, String>, String>() {
3musket33rs/mathsync
integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
private final Summarizer summarizer = SummarizerFromItems.simple(content.entrySet(), StringSerializer.create(new Function<Entry<String, String>, String>() {
3musket33rs/mathsync
integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function;
package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
// Path: java/core/src/main/java/eu/mais_h/mathsync/Summarizer.java // public interface Summarizer { // // /** // * Produces a summary at a given level of detail. // * // * <p>The larger detail level is, the bigger summary will consume on the wire, but the more // * information it conveys.</p> // * // * @param level the level of detail. // * @return a summary of the current state at the requested level of detail. // */ // Summary summarize(int level); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java // public class SummarizerFromItems implements Summarizer { // // private final SerializedItems items; // private final Digester digester; // private final BucketSelector selector; // // SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { // this.items = items; // this.digester = digester; // this.selector = selector; // } // // /** // * {@inheritDoc} // * // * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> // */ // @Override // public Summary summarize(int level) { // int size = Defaults.ibfSizeFromLevel(level); // Summary empty; // if (size > items.size()) { // empty = FullContent.EMPTY; // } else { // empty = new Ibf(size, digester, selector); // } // Summary filled = empty.plus(items.iterator()); // return filled; // } // // /** // * Builds a simple summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. // */ // public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) { // return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector()); // } // // /** // * Builds a custom summarizer. // * // * @param items the set of containing all items in the current state. // * @param serializer the serializer to use to serialize items. // * @param digester the custom digester to use. // * @param selector the strategy to choose buckets to store items in. // * @return a summarizer corresponding to the input. // */ // public static <T> Summarizer custom(Set<? extends T> items, Serializer<? super T> serializer, Digester digester, BucketSelector selector) { // return new SummarizerFromItems(new SerializedItems(items, serializer), digester, selector); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/StringSerializer.java // public class StringSerializer<T> implements Serializer<T> { // // private final Function<T, String> toString; // // private StringSerializer(Function<T, String> toString) { // this.toString = toString; // } // // @Override // public byte[] serialize(T item) { // String stringified = toString.apply(item); // byte[] result; // try { // result = stringified.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new AssertionError("JVM does not support UTF-8 encoding"); // } // return result; // } // // /** // * Retrieves an instance of this serializer. // * // * @param toString the function to convert items to string as an intermediate representation. // * @return an instance of this serializer kind. // */ // public static <T> Serializer<T> create(Function<T, String> toString) { // return new StringSerializer<>(toString); // } // // /** // * Retrieves an instance of this serializer directly serializing strings. // * // * @return an instance of this serializer kind. // */ // public static Serializer<String> create() { // return create(new Function<String, String>() { // // @Override // public String apply(String t) { // return t; // } // }); // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/util/Function.java // public interface Function<T, R> { // // /** // * Applies this function to the given argument. // * // * @param t the function argument. // * @return the function result. // */ // R apply(T t); // } // Path: integration-test/java-webapp/src/main/java/eu/mais_h/mathsync/test/SummaryServlet.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import eu.mais_h.mathsync.Summarizer; import eu.mais_h.mathsync.SummarizerFromItems; import eu.mais_h.mathsync.serialize.StringSerializer; import eu.mais_h.mathsync.util.Function; package eu.mais_h.mathsync.test; public class SummaryServlet extends HttpServlet { private static final long serialVersionUID = 8629863338196207094L; private final Map<String, String> content = Collections.synchronizedMap(new HashMap<String, String>());
private final Summarizer summarizer = SummarizerFromItems.simple(content.entrySet(), StringSerializer.create(new Function<Entry<String, String>, String>() {
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/Ibf.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // }
import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.json.JSONArray; import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester;
package eu.mais_h.mathsync; class Ibf implements Summary { private final Bucket[] buckets; private final BucketSelector selector;
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/Ibf.java import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.json.JSONArray; import org.json.JSONTokener; import eu.mais_h.mathsync.digest.Digester; package eu.mais_h.mathsync; class Ibf implements Summary { private final Bucket[] buckets; private final BucketSelector selector;
private final Digester digester;
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/PadAndHashBucketSelector.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // }
import java.nio.ByteBuffer; import java.util.Arrays; import eu.mais_h.mathsync.digest.Digester;
package eu.mais_h.mathsync; /** * Pads content and hashes it to select buckets. */ public class PadAndHashBucketSelector implements BucketSelector { private static final int BYTES_PER_INT = 4; private final int spread;
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/PadAndHashBucketSelector.java import java.nio.ByteBuffer; import java.util.Arrays; import eu.mais_h.mathsync.digest.Digester; package eu.mais_h.mathsync; /** * Pads content and hashes it to select buckets. */ public class PadAndHashBucketSelector implements BucketSelector { private static final int BYTES_PER_INT = 4; private final int spread;
private final Digester digester;
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items;
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items;
private final Digester digester;
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items; private final Digester digester; private final BucketSelector selector; SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { this.items = items; this.digester = digester; this.selector = selector; } /** * {@inheritDoc} * * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> */ @Override public Summary summarize(int level) { int size = Defaults.ibfSizeFromLevel(level); Summary empty; if (size > items.size()) { empty = FullContent.EMPTY; } else { empty = new Ibf(size, digester, selector); } Summary filled = empty.plus(items.iterator()); return filled; } /** * Builds a simple summarizer. * * @param items the set of containing all items in the current state. * @param serializer the serializer to use to serialize items. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. */
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items; private final Digester digester; private final BucketSelector selector; SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { this.items = items; this.digester = digester; this.selector = selector; } /** * {@inheritDoc} * * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> */ @Override public Summary summarize(int level) { int size = Defaults.ibfSizeFromLevel(level); Summary empty; if (size > items.size()) { empty = FullContent.EMPTY; } else { empty = new Ibf(size, digester, selector); } Summary filled = empty.plus(items.iterator()); return filled; } /** * Builds a simple summarizer. * * @param items the set of containing all items in the current state. * @param serializer the serializer to use to serialize items. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. */
public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) {
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items; private final Digester digester; private final BucketSelector selector; SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { this.items = items; this.digester = digester; this.selector = selector; } /** * {@inheritDoc} * * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> */ @Override public Summary summarize(int level) { int size = Defaults.ibfSizeFromLevel(level); Summary empty; if (size > items.size()) { empty = FullContent.EMPTY; } else { empty = new Ibf(size, digester, selector); } Summary filled = empty.plus(items.iterator()); return filled; } /** * Builds a simple summarizer. * * @param items the set of containing all items in the current state. * @param serializer the serializer to use to serialize items. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. */ public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) {
// Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Digester.java // public interface Digester { // // /** // * Digests an item serialized as an array of bytes. // * // * <p>Any byte array value must be accepted and have a non <code>null</code> return value: for any <code>a</code>, // * <code>digest(a) != null</code>.</p> // * // * <p>All valid inputs should produce in output an array of the same size:for any <code>a1</code> and // * <code>a2</code>, <code>digest(a1).length == digest(a2).length</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the same array: for // * any <code>a1</code> and <code>a2</code>, <code>Arrays.equals(a1, a2)</code> implies // * <code>Arrays.equals(digest(a1), digest(a2))</code>.</p> // * // * <p>In addition to those constrains, it is recommended that it has the properties of a // * <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash function</a>.</p> // * // * @param source the item serialized as an array of bytes. // * @return the message digest of the item. // * @throws IllegalArgumentException if the input array is <code>null</code>. // */ // byte[] digest(byte[] source); // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/digest/Sha1Digester.java // public class Sha1Digester implements Digester { // // private static final String DIGEST_ALGORITHM = "SHA-1"; // private static final Sha1Digester INSTANCE = new Sha1Digester(); // // private Sha1Digester() { // } // // /** // * Digests according to SHA-1 specification. // */ // @Override // public byte[] digest(byte[] source) { // if (source == null) { // throw new IllegalArgumentException("Cannot digest null source"); // } // // MessageDigest md; // try { // md = MessageDigest.getInstance(DIGEST_ALGORITHM); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError("JVM does not support " + DIGEST_ALGORITHM + " algorithm", e); // } // md.update(source); // return md.digest(); // } // // @Override // public String toString() { // return DIGEST_ALGORITHM; // } // // /** // * Retrieves an instance of this digester kind. // * // * @return an instance of this digester kind. // */ // public static Sha1Digester get() { // return INSTANCE; // } // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SummarizerFromItems.java import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.digest.Digester; import eu.mais_h.mathsync.digest.Sha1Digester; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; /** * Summarizer which iterates on items in the current state to build summaries. */ public class SummarizerFromItems implements Summarizer { private final SerializedItems items; private final Digester digester; private final BucketSelector selector; SummarizerFromItems(SerializedItems items, Digester digester, BucketSelector selector) { this.items = items; this.digester = digester; this.selector = selector; } /** * {@inheritDoc} * * <p>Summaries produced have a size of <code>O(2^level)</code>.</p> */ @Override public Summary summarize(int level) { int size = Defaults.ibfSizeFromLevel(level); Summary empty; if (size > items.size()) { empty = FullContent.EMPTY; } else { empty = new Ibf(size, digester, selector); } Summary filled = empty.plus(items.iterator()); return filled; } /** * Builds a simple summarizer. * * @param items the set of containing all items in the current state. * @param serializer the serializer to use to serialize items. * @return a summarizer with {@link Sha1Digester SHA-1 digester} and default spread. */ public static <T> Summarizer simple(Set<? extends T> items, Serializer<? super T> serializer) {
return custom(items, serializer, Sha1Digester.get(), Defaults.defaultSelector());
3musket33rs/mathsync
java/core/src/test/java/eu/mais_h/mathsync/DeserializedDifferenceTest.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // }
import static org.fest.assertions.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import eu.mais_h.mathsync.serialize.Deserializer;
package eu.mais_h.mathsync; public class DeserializedDifferenceTest { @SuppressWarnings("unchecked") Difference<byte[]> serialized = Mockito.mock(Difference.class); @SuppressWarnings("unchecked")
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // Path: java/core/src/test/java/eu/mais_h/mathsync/DeserializedDifferenceTest.java import static org.fest.assertions.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import eu.mais_h.mathsync.serialize.Deserializer; package eu.mais_h.mathsync; public class DeserializedDifferenceTest { @SuppressWarnings("unchecked") Difference<byte[]> serialized = Mockito.mock(Difference.class); @SuppressWarnings("unchecked")
Deserializer<String> deserializer = Mockito.mock(Deserializer.class);
3musket33rs/mathsync
java/core/src/test/java/eu/mais_h/mathsync/ResolverFromItemsTest.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // }
import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import java.util.Collections; import java.util.Iterator; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import eu.mais_h.mathsync.serialize.Deserializer;
package eu.mais_h.mathsync; public class ResolverFromItemsTest { @SuppressWarnings("unchecked") private Iterable<byte[]> local = Mockito.mock(Iterable.class); @SuppressWarnings("unchecked") private Iterator<byte[]> iterator = Mockito.mock(Iterator.class); private String localElement = "element1"; private byte[] localContent = new byte[] { (byte)1, (byte)2 }; private String remoteElement = "element2"; private byte[] remoteContent = new byte[] { (byte)3, (byte)4 }; @SuppressWarnings("unchecked") private Difference<byte[]> difference = Mockito.mock(Difference.class); private Summarizer remote = Mockito.mock(Summarizer.class); @SuppressWarnings("unchecked")
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // Path: java/core/src/test/java/eu/mais_h/mathsync/ResolverFromItemsTest.java import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import java.util.Collections; import java.util.Iterator; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import eu.mais_h.mathsync.serialize.Deserializer; package eu.mais_h.mathsync; public class ResolverFromItemsTest { @SuppressWarnings("unchecked") private Iterable<byte[]> local = Mockito.mock(Iterable.class); @SuppressWarnings("unchecked") private Iterator<byte[]> iterator = Mockito.mock(Iterator.class); private String localElement = "element1"; private byte[] localContent = new byte[] { (byte)1, (byte)2 }; private String remoteElement = "element2"; private byte[] remoteContent = new byte[] { (byte)3, (byte)4 }; @SuppressWarnings("unchecked") private Difference<byte[]> difference = Mockito.mock(Difference.class); private Summarizer remote = Mockito.mock(Summarizer.class); @SuppressWarnings("unchecked")
private Deserializer<String> deserializer = Mockito.mock(Deserializer.class);
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/ResolverFromItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; /** * Resolver using a remote summarizer to compute the delta. * * @param <T> the type of compared items. */ public class ResolverFromItems<T> implements Resolver<T> { private final Iterable<byte[]> items; private final Summarizer remote;
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/ResolverFromItems.java import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; /** * Resolver using a remote summarizer to compute the delta. * * @param <T> the type of compared items. */ public class ResolverFromItems<T> implements Resolver<T> { private final Iterable<byte[]> items; private final Summarizer remote;
private final Deserializer<T> deserializer;
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/ResolverFromItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; /** * Resolver using a remote summarizer to compute the delta. * * @param <T> the type of compared items. */ public class ResolverFromItems<T> implements Resolver<T> { private final Iterable<byte[]> items; private final Summarizer remote; private final Deserializer<T> deserializer; ResolverFromItems(Iterable<byte[]> items, Summarizer remote, Deserializer<T> deserializer) { this.items = items; this.remote = remote; this.deserializer = deserializer; } @Override public Difference<T> difference() { int level = 0; Difference<byte[]> difference = null; while (difference == null) { level++; Summary remoteIbf = remote.summarize(level); Summary minusLocal = remoteIbf.minus(items.iterator()); difference = minusLocal.toDifference(); } return new DeserializedDifference<T>(difference, deserializer); } /** * Builds a simple resolver. * * @param items the set containing all items in the current state. * @param serializer the serializer to use to serialize items. * @param remote the retriever of remote state. * @param deserializer the deserializer to use to deserialize items. * @return a summarizer with SHA-1 digester and default spread. */
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Deserializer.java // public interface Deserializer<T> { // // /** // * Deserializes an array of bytes back to an object. // * // * <p>Any array of bytes should lead to either a non <code>null</code> value or throw an // * {@link IllegalArgumentException}.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice // * on the identical arrays: for any valid <code>a1</code> and <code>a2</code>, // * <code>Arrays.equals(a1, a2)</code> implies // * <code>deserialize(a1).equals(deserialize(a2))</code>.</p> // * // * @param content the array of bytes representing an object. // * @return the object deserialized from the array of bytes. // * @throws IllegalArgumentException if the input array does not denote a valid object. // */ // T deserialize(byte[] content) throws IllegalArgumentException; // } // // Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/ResolverFromItems.java import java.util.Set; import eu.mais_h.mathsync.serialize.Deserializer; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; /** * Resolver using a remote summarizer to compute the delta. * * @param <T> the type of compared items. */ public class ResolverFromItems<T> implements Resolver<T> { private final Iterable<byte[]> items; private final Summarizer remote; private final Deserializer<T> deserializer; ResolverFromItems(Iterable<byte[]> items, Summarizer remote, Deserializer<T> deserializer) { this.items = items; this.remote = remote; this.deserializer = deserializer; } @Override public Difference<T> difference() { int level = 0; Difference<byte[]> difference = null; while (difference == null) { level++; Summary remoteIbf = remote.summarize(level); Summary minusLocal = remoteIbf.minus(items.iterator()); difference = minusLocal.toDifference(); } return new DeserializedDifference<T>(difference, deserializer); } /** * Builds a simple resolver. * * @param items the set containing all items in the current state. * @param serializer the serializer to use to serialize items. * @param remote the retriever of remote state. * @param deserializer the deserializer to use to deserialize items. * @return a summarizer with SHA-1 digester and default spread. */
public static <T> Resolver<T> from(Set<? extends T> items, Serializer<? super T> serializer, Summarizer remote, Deserializer<T> deserializer) {
3musket33rs/mathsync
java/core/src/main/java/eu/mais_h/mathsync/SerializedItems.java
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // }
import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.serialize.Serializer;
package eu.mais_h.mathsync; class SerializedItems<T> implements Iterable<byte[]> { private final Set<? extends T> items;
// Path: java/core/src/main/java/eu/mais_h/mathsync/serialize/Serializer.java // public interface Serializer<T> { // // /** // * Serializes an object to an array of byte. // * // * <p>Any instance of <code>T</code> must be accepted and have a non <code>null</code> return value: // * for any <code>o</code>, <code>o instanceof T</code> implies <code>serialize(o) != null</code>.</p> // * // * <p>The output must be consistent, an identical output should be returned if called twice on the equal // * objects: for any <code>o1</code> and <code>o2</code>, <code>o1.equals(o2)</code> implies // * <code>Arrays.equals(serialize(o1), serialize(o2))</code>.</p> // * // * @param item the object to serialize. // * @return the array of bytes representing the input object on the wire. // */ // byte[] serialize(T item); // } // Path: java/core/src/main/java/eu/mais_h/mathsync/SerializedItems.java import java.util.Iterator; import java.util.Set; import eu.mais_h.mathsync.serialize.Serializer; package eu.mais_h.mathsync; class SerializedItems<T> implements Iterable<byte[]> { private final Set<? extends T> items;
private final Serializer<? super T> serializer;
dkzwm/SmoothRefreshLayout
app/src/main/java/me/dkzwm/widget/srl/sample/ui/TestMaterialStyleActivity.java
// Path: ext-material/src/main/java/me/dkzwm/widget/srl/MaterialSmoothRefreshLayout.java // public class MaterialSmoothRefreshLayout extends SmoothRefreshLayout { // protected OnUIPositionChangedListener mOnUIPositionChangedListener = // new OnUIPositionChangedListener() { // int mLastMovingStatus = Constants.MOVING_CONTENT; // // @Override // public void onChanged(byte status, IIndicator indicator) { // int movingStatus = indicator.getMovingStatus(); // if (movingStatus == Constants.MOVING_HEADER) { // if (movingStatus != mLastMovingStatus) { // setEnablePinRefreshViewWhileLoading(true); // } // } else { // if (movingStatus != mLastMovingStatus) { // setEnablePinContentView(false); // } // } // mLastMovingStatus = movingStatus; // } // }; // // public MaterialSmoothRefreshLayout(Context context) { // super(context); // } // // public MaterialSmoothRefreshLayout(Context context, AttributeSet attrs) { // super(context, attrs); // } // // public MaterialSmoothRefreshLayout(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // @Override // protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super.init(context, attrs, defStyleAttr, defStyleRes); // MaterialHeader header = new MaterialHeader(context); // header.setColorSchemeColors(new int[] {Color.RED, Color.BLUE, Color.GREEN, Color.BLACK}); // header.setPadding(0, PixelUtl.dp2px(context, 25), 0, PixelUtl.dp2px(context, 20)); // setHeaderView(header); // MaterialFooter footer = new MaterialFooter(context); // setFooterView(footer); // } // // /** // * Quickly set to material style. Before you change the configuration, you must know which // * parameters have been configured // */ // public void materialStyle() { // setRatioOfFooterToRefresh(.95f); // setMaxMoveRatioOfFooter(1f); // setRatioToKeep(1f); // setMaxMoveRatioOfHeader(1.5f); // setEnablePinContentView(true); // setEnableKeepRefreshView(true); // if (mHeaderView instanceof MaterialHeader) // ((MaterialHeader) mHeaderView).doHookUIRefreshComplete(this); // if (!isDisabledLoadMore()) { // addOnUIPositionChangedListener(mOnUIPositionChangedListener); // } // } // } // // Path: core/src/main/java/me/dkzwm/widget/srl/RefreshingListenerAdapter.java // public abstract class RefreshingListenerAdapter implements SmoothRefreshLayout.OnRefreshListener { // @Override // public void onRefreshing() {} // // @Override // public void onLoadingMore() {} // }
import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout; import me.dkzwm.widget.srl.RefreshingListenerAdapter; import me.dkzwm.widget.srl.sample.R;
package me.dkzwm.widget.srl.sample.ui; /** * Created by dkzwm on 2017/6/1. * * @author dkzwm */ public class TestMaterialStyleActivity extends AppCompatActivity { private MaterialSmoothRefreshLayout mRefreshLayout; private TextView mTextView; private Handler mHandler = new Handler(); private int mCount = 0; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_refresh); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle(R.string.test_material_style); mTextView = findViewById(R.id.textView_test_refresh_desc); mRefreshLayout = findViewById(R.id.smoothRefreshLayout_test_refresh); mRefreshLayout.materialStyle(); mRefreshLayout.setOnRefreshListener(
// Path: ext-material/src/main/java/me/dkzwm/widget/srl/MaterialSmoothRefreshLayout.java // public class MaterialSmoothRefreshLayout extends SmoothRefreshLayout { // protected OnUIPositionChangedListener mOnUIPositionChangedListener = // new OnUIPositionChangedListener() { // int mLastMovingStatus = Constants.MOVING_CONTENT; // // @Override // public void onChanged(byte status, IIndicator indicator) { // int movingStatus = indicator.getMovingStatus(); // if (movingStatus == Constants.MOVING_HEADER) { // if (movingStatus != mLastMovingStatus) { // setEnablePinRefreshViewWhileLoading(true); // } // } else { // if (movingStatus != mLastMovingStatus) { // setEnablePinContentView(false); // } // } // mLastMovingStatus = movingStatus; // } // }; // // public MaterialSmoothRefreshLayout(Context context) { // super(context); // } // // public MaterialSmoothRefreshLayout(Context context, AttributeSet attrs) { // super(context, attrs); // } // // public MaterialSmoothRefreshLayout(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // @Override // protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super.init(context, attrs, defStyleAttr, defStyleRes); // MaterialHeader header = new MaterialHeader(context); // header.setColorSchemeColors(new int[] {Color.RED, Color.BLUE, Color.GREEN, Color.BLACK}); // header.setPadding(0, PixelUtl.dp2px(context, 25), 0, PixelUtl.dp2px(context, 20)); // setHeaderView(header); // MaterialFooter footer = new MaterialFooter(context); // setFooterView(footer); // } // // /** // * Quickly set to material style. Before you change the configuration, you must know which // * parameters have been configured // */ // public void materialStyle() { // setRatioOfFooterToRefresh(.95f); // setMaxMoveRatioOfFooter(1f); // setRatioToKeep(1f); // setMaxMoveRatioOfHeader(1.5f); // setEnablePinContentView(true); // setEnableKeepRefreshView(true); // if (mHeaderView instanceof MaterialHeader) // ((MaterialHeader) mHeaderView).doHookUIRefreshComplete(this); // if (!isDisabledLoadMore()) { // addOnUIPositionChangedListener(mOnUIPositionChangedListener); // } // } // } // // Path: core/src/main/java/me/dkzwm/widget/srl/RefreshingListenerAdapter.java // public abstract class RefreshingListenerAdapter implements SmoothRefreshLayout.OnRefreshListener { // @Override // public void onRefreshing() {} // // @Override // public void onLoadingMore() {} // } // Path: app/src/main/java/me/dkzwm/widget/srl/sample/ui/TestMaterialStyleActivity.java import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout; import me.dkzwm.widget.srl.RefreshingListenerAdapter; import me.dkzwm.widget.srl.sample.R; package me.dkzwm.widget.srl.sample.ui; /** * Created by dkzwm on 2017/6/1. * * @author dkzwm */ public class TestMaterialStyleActivity extends AppCompatActivity { private MaterialSmoothRefreshLayout mRefreshLayout; private TextView mTextView; private Handler mHandler = new Handler(); private int mCount = 0; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_refresh); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle(R.string.test_material_style); mTextView = findViewById(R.id.textView_test_refresh_desc); mRefreshLayout = findViewById(R.id.smoothRefreshLayout_test_refresh); mRefreshLayout.materialStyle(); mRefreshLayout.setOnRefreshListener(
new RefreshingListenerAdapter() {
Turksat/ESign
ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/view/container/MainApplet.java
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/controller/GUIManager.java // public class GUIManager { // public static RootPaneContainer mainContainer; // public static JPanel curPane; // // /** // * Removes old screen with given pane. // * // * @param pane // */ // public static void changeScreen(JPanel pane) { // mainContainer.getContentPane().remove(curPane); // curPane = pane; // mainContainer.getContentPane().add(pane); // mainContainer.getContentPane().repaint(); // GUIHelper.requestFocus(pane); // } // // /** // * Searches pane with given name inside current panel. // * If pane is found, replaces old pane with new pane. // * // * @param oldPaneName // * @param newPane // */ // public static void replacePane(String oldPaneName, JPanel newPane) { // Component[] components = curPane.getComponents(); // JPanel oldPane = null; // for(Component comp: components) { // if(comp.getName()!=null&&comp.getName().equals(oldPaneName)&&comp instanceof JPanel) { // oldPane = (JPanel) comp; // break; // } // } // if(oldPane==null) { // GUIManager.showErrMsg("Component "+oldPaneName+ " not found"); // } else { // newPane.setLocation(oldPane.getX(),oldPane.getY()); // newPane.setSize(oldPane.getWidth(),oldPane.getHeight()); // curPane.remove(oldPane); // curPane.add(newPane); // curPane.repaint(); // GUIHelper.requestFocus(newPane); // } // } // // /** // * Initialize main container as RootPaneContainer(such as japplet or jframe) // * @param container // */ // public static void init(RootPaneContainer container) { // mainContainer = container; // curPane = new CardSelectScreen(); // mainContainer.getContentPane().add(curPane); // ((Container)mainContainer).setVisible(true); // } // // /** // * Destroys main container. // */ // public static void destroy() { // if(mainContainer instanceof Window) { // ((Window)mainContainer).dispose(); // } else { // //do nothing // } // } // // /** // * Shows error message to user. // * @param msg // */ // public static void showErrMsg(String msg) { // JOptionPane.showMessageDialog((Container)mainContainer, msg); // } // // }
import javax.swing.JPanel; import tr.gov.turkiye.esignuidesk.controller.GUIManager; import javax.swing.JApplet;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.view.container; /** * * @author iakpolat */ public class MainApplet extends JApplet { private JPanel curPane; /** * Initialization method that will be called after the applet is loaded into * the browser. */ @Override public void init() { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setLayout(null); setBounds(0,0,530,250);
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/controller/GUIManager.java // public class GUIManager { // public static RootPaneContainer mainContainer; // public static JPanel curPane; // // /** // * Removes old screen with given pane. // * // * @param pane // */ // public static void changeScreen(JPanel pane) { // mainContainer.getContentPane().remove(curPane); // curPane = pane; // mainContainer.getContentPane().add(pane); // mainContainer.getContentPane().repaint(); // GUIHelper.requestFocus(pane); // } // // /** // * Searches pane with given name inside current panel. // * If pane is found, replaces old pane with new pane. // * // * @param oldPaneName // * @param newPane // */ // public static void replacePane(String oldPaneName, JPanel newPane) { // Component[] components = curPane.getComponents(); // JPanel oldPane = null; // for(Component comp: components) { // if(comp.getName()!=null&&comp.getName().equals(oldPaneName)&&comp instanceof JPanel) { // oldPane = (JPanel) comp; // break; // } // } // if(oldPane==null) { // GUIManager.showErrMsg("Component "+oldPaneName+ " not found"); // } else { // newPane.setLocation(oldPane.getX(),oldPane.getY()); // newPane.setSize(oldPane.getWidth(),oldPane.getHeight()); // curPane.remove(oldPane); // curPane.add(newPane); // curPane.repaint(); // GUIHelper.requestFocus(newPane); // } // } // // /** // * Initialize main container as RootPaneContainer(such as japplet or jframe) // * @param container // */ // public static void init(RootPaneContainer container) { // mainContainer = container; // curPane = new CardSelectScreen(); // mainContainer.getContentPane().add(curPane); // ((Container)mainContainer).setVisible(true); // } // // /** // * Destroys main container. // */ // public static void destroy() { // if(mainContainer instanceof Window) { // ((Window)mainContainer).dispose(); // } else { // //do nothing // } // } // // /** // * Shows error message to user. // * @param msg // */ // public static void showErrMsg(String msg) { // JOptionPane.showMessageDialog((Container)mainContainer, msg); // } // // } // Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/view/container/MainApplet.java import javax.swing.JPanel; import tr.gov.turkiye.esignuidesk.controller.GUIManager; import javax.swing.JApplet; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.view.container; /** * * @author iakpolat */ public class MainApplet extends JApplet { private JPanel curPane; /** * Initialization method that will be called after the applet is loaded into * the browser. */ @Override public void init() { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { setLayout(null); setBounds(0,0,530,250);
GUIManager.init(MainApplet.this);
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9};
import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() {
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9}; // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() {
OSNames systemOS = OS.getSystemOS();
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9};
import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() {
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9}; // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() {
OSNames systemOS = OS.getSystemOS();
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9};
import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) {
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9}; // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.manager; /** * * @author sercan */ public class LibraryManager { /** * Loads wrapper library for current operating system. * * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper() { try { System.loadLibrary("pkcs11wrapper"); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) {
OSArch systemOSArch = OS.getSystemOSArch();
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9};
import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion;
/** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) {
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9}; // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion; /** * Loads pkcs wrapper library by path. * * @param libPath * @return If library is loaded successfully or already loaded return true, otherwise false. */ public static boolean loadPKCS11Wrapper(String libPath) { try { System.load(libPath); } catch (final Throwable t) { t.printStackTrace(System.err); if (t.getMessage().toLowerCase().contains("already loaded")) { return true; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) {
return LibConfig.WINDOWS64_LIB_PATH;
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9};
import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion;
} return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) { return LibConfig.WINDOWS64_LIB_PATH; } else { return LibConfig.WINDOWS32_LIB_PATH; } } else if (systemOS.equals(OSNames.LINUX)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) { return LibConfig.LINUX64_LIB_PATH; } else { return LibConfig.LINUX32_LIB_PATH; } } else if (systemOS.equals(OSNames.MACOS)) { return LibConfig.MACOS_LIB_PATH; } else if (systemOS.equals(OSNames.SOLARIS)) {
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/LibConfig.java // public class LibConfig { // public static final String WINDOWS32_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String WINDOWS64_LIB_NAME = "PKCS11Wrapper.dll"; // public static final String LINUX_LIB_NAME = "libpkcs11wrapper.so"; // public static final String MACOS_LIB_NAME = "libpkcs11wrapper.jnilib"; // public static final String SOLARIS_LIB_NAME = "libpkcs11wrapper.so"; // public static final String OTHER_LIB_NAME = "libpkcs11wrapper.so"; // // public static final String WINDOWS32_LIB_PATH = "libs/windows/32/"+WINDOWS32_LIB_NAME; // public static final String WINDOWS64_LIB_PATH = "libs/windows/64/"+WINDOWS64_LIB_NAME; // public static final String LINUX32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String LINUX64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // public static final String MACOS_LIB_PATH = "libs/macos/"+MACOS_LIB_NAME; // public static final String SOLARIS_LIB_PATH = "libs/solaris/"+SOLARIS_LIB_NAME; // public static final String SOLARIS_V9_LIB_PATH = "libs/solaris/v9/"+SOLARIS_LIB_NAME; // //Other operating systems are assumed as linux. // public static final String OTHER32_LIB_PATH = "libs/linux/32/"+LINUX_LIB_NAME; // public static final String OTHER64_LIB_PATH = "libs/linux/64/"+LINUX_LIB_NAME; // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/statics/OS.java // public class OS { // final private static String WINDOWS = "windows"; // final private static String LINUX = "linux"; // final private static String MACOS = "mac"; // final private static String SOLARIS = "solaris"; // // /** // * Gets user operating system. // * // * @return Return corresponding OS name. If user operation system is not supported returns OSNames.OTHER // */ // public static OSNames getSystemOS() { // String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if (osName.contains(WINDOWS)) { // return OSNames.WINDOWS; // } else if (osName.contains(LINUX)) { // return OSNames.LINUX; // } else if (osName.contains(MACOS)) { // return OSNames.MACOS; // } else if(osName.contains(SOLARIS)){ // return OSNames.SOLARIS; // }else{ // return OSNames.OTHER; // } // } // // /** // * Gets bits of operating system. // * // * @return // */ // public static OSArch getSystemOSArch() { // String osAcrh = System.getProperty("os.arch").toLowerCase(Locale.ENGLISH); // if (osAcrh.contains("64")) { // return OSArch._64BIT; // } else { // return OSArch._32BIT; // } // } // // /** // * Gets system version from Solaris operation system. // * // * @return // */ // public static OSVersion getSystemOSVersionForSolaris() { // String osVersion = System.getProperty("os.version").toLowerCase(Locale.ENGLISH); // if (osVersion.contains("V9")) { // return OSVersion.SPARC_V9; // } else{ // return OSVersion.SPARC; // } // } // // // // } // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSArch.java // public enum OSArch {_32BIT, _64BIT}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSNames.java // public enum OSNames {WINDOWS, LINUX, MACOS, OTHER, SOLARIS}; // // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/enums/OSVersion.java // public enum OSVersion {SPARC, SPARC_V9}; // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/manager/LibraryManager.java import tr.gov.turkiye.esign.statics.LibConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import tr.gov.turkiye.esign.statics.OS; import tr.gov.turkiye.esign.enums.OSArch; import tr.gov.turkiye.esign.enums.OSNames; import tr.gov.turkiye.esign.enums.OSVersion; } return t.getLocalizedMessage().contains("already loaded"); } return true; } /** * Gets directory which contains installation packages. * * @return */ private static String getInstallDir() { OSNames systemOS = OS.getSystemOS(); if (systemOS.equals(OSNames.WINDOWS)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) { return LibConfig.WINDOWS64_LIB_PATH; } else { return LibConfig.WINDOWS32_LIB_PATH; } } else if (systemOS.equals(OSNames.LINUX)) { OSArch systemOSArch = OS.getSystemOSArch(); if (systemOSArch.equals(OSArch._64BIT)) { return LibConfig.LINUX64_LIB_PATH; } else { return LibConfig.LINUX32_LIB_PATH; } } else if (systemOS.equals(OSNames.MACOS)) { return LibConfig.MACOS_LIB_PATH; } else if (systemOS.equals(OSNames.SOLARIS)) {
OSVersion systemOSVersion = OS.getSystemOSVersionForSolaris();
Turksat/ESign
ESignCore/src/main/java/tr/gov/turkiye/esign/support/StringSupport.java
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/support/Util.java // final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import static tr.gov.turkiye.esign.support.Util.hexArray;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.support; /** * * @author iakpolat */ public class StringSupport { /** * @param bytes * @return hex representation of bytes */ public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF;
// Path: ESignCore/src/main/java/tr/gov/turkiye/esign/support/Util.java // final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); // Path: ESignCore/src/main/java/tr/gov/turkiye/esign/support/StringSupport.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import static tr.gov.turkiye.esign.support.Util.hexArray; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esign.support; /** * * @author iakpolat */ public class StringSupport { /** * @param bytes * @return hex representation of bytes */ public static String bytesToHex(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];
Turksat/ESign
ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/data/UserData.java
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/props/ScreenProperties.java // public class ScreenProperties { // private static ResourceBundle bundle; // // public static String getValue(final String key) { // if (bundle == null) { // bundle = ResourceBundle.getBundle("screen_values", Config.locale); // } // return bundle.getString(key); // } // // }
import java.util.ArrayList; import java.util.List; import tr.gov.turkiye.esignuidesk.props.ScreenProperties; import java.security.cert.X509Certificate;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.data; /** * Holds user data during runtime. * * @author iakpolat */ public class UserData { /** * User certificates in card */ public static List<X509Certificate> certs = new ArrayList<>(); /** * Selected card type */ public static String slcCardType = null; /** * Selected certificate index */ public static int slcCertIndex = 0; /** * Pin password */ public static char[] pinPass; /** * User agreement data different to each user since it contains time. */
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/props/ScreenProperties.java // public class ScreenProperties { // private static ResourceBundle bundle; // // public static String getValue(final String key) { // if (bundle == null) { // bundle = ResourceBundle.getBundle("screen_values", Config.locale); // } // return bundle.getString(key); // } // // } // Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/data/UserData.java import java.util.ArrayList; import java.util.List; import tr.gov.turkiye.esignuidesk.props.ScreenProperties; import java.security.cert.X509Certificate; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.data; /** * Holds user data during runtime. * * @author iakpolat */ public class UserData { /** * User certificates in card */ public static List<X509Certificate> certs = new ArrayList<>(); /** * Selected card type */ public static String slcCardType = null; /** * Selected certificate index */ public static int slcCertIndex = 0; /** * Pin password */ public static char[] pinPass; /** * User agreement data different to each user since it contains time. */
public static String userAgreement = ScreenProperties.getValue("data_to_be_signed");
Turksat/ESign
ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/view/container/MainFrame.java
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/config/Config.java // public class Config { // //Main frame configuration // public static final int FRAME_WIDTH = 530; // public static final int FRAME_HEIGHT = 275; // public static final int FRAME_STARTING_X = 30; // public static final int FRAME_STARTING_Y = 30; // // //Main panel configuration // public static final int DEF_PANEL_WIDTH = FRAME_WIDTH; // public static final int DEF_PANEL_HEIGHT = FRAME_HEIGHT-25; // public static final int DEF_PANEL_STARTING_X = 0; // public static final int DEF_PANEL_STARTING_Y = 0; // // public static final Locale locale = new Locale("tr","TR"); // // public static final Locale locale = new Locale("en","EN"); // // //Screen ids are used on logic manager to interpret where requests are coming from. // public static final int CARD_SELECT_SCREEN_ID = 1; // public static final int CERT_SHOW_SCREEN_ID = 2; // public static final int PIN_PANE_ID = 3; // public static final int DONE_PANE_ID = 4; // // public static final int DEBUG_TYPE = 1; //0=do nothing,1=print stack trace to console,2=print localized message to console, 3=send to server etc. // // public static final String certInfoPaneName = "certInfoPane"; // public static final String certPaneName = "certPane"; // public static final String pinPaneName = "pinPane"; // // public static final Point pinBtnStartPoint = new Point(20, 60); // public static final Dimension numberBtnSize = new Dimension(40,40); // // public static final String defaultFileName = "signed_document_"; // // public static final String dateSFormat = "dd.MM.yyyy"; // public static final String timeSFormat = "dd-MM-yyyy_hh_mm_ss"; // }
import tr.gov.turkiye.esignuidesk.config.Config; import javax.swing.JPanel;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.view.container; /** * * @author iakpolat */ public class MainFrame extends javax.swing.JFrame { /** * Creates new form Main */ public MainFrame() { initComponents();
// Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/config/Config.java // public class Config { // //Main frame configuration // public static final int FRAME_WIDTH = 530; // public static final int FRAME_HEIGHT = 275; // public static final int FRAME_STARTING_X = 30; // public static final int FRAME_STARTING_Y = 30; // // //Main panel configuration // public static final int DEF_PANEL_WIDTH = FRAME_WIDTH; // public static final int DEF_PANEL_HEIGHT = FRAME_HEIGHT-25; // public static final int DEF_PANEL_STARTING_X = 0; // public static final int DEF_PANEL_STARTING_Y = 0; // // public static final Locale locale = new Locale("tr","TR"); // // public static final Locale locale = new Locale("en","EN"); // // //Screen ids are used on logic manager to interpret where requests are coming from. // public static final int CARD_SELECT_SCREEN_ID = 1; // public static final int CERT_SHOW_SCREEN_ID = 2; // public static final int PIN_PANE_ID = 3; // public static final int DONE_PANE_ID = 4; // // public static final int DEBUG_TYPE = 1; //0=do nothing,1=print stack trace to console,2=print localized message to console, 3=send to server etc. // // public static final String certInfoPaneName = "certInfoPane"; // public static final String certPaneName = "certPane"; // public static final String pinPaneName = "pinPane"; // // public static final Point pinBtnStartPoint = new Point(20, 60); // public static final Dimension numberBtnSize = new Dimension(40,40); // // public static final String defaultFileName = "signed_document_"; // // public static final String dateSFormat = "dd.MM.yyyy"; // public static final String timeSFormat = "dd-MM-yyyy_hh_mm_ss"; // } // Path: ESignUI/src/main/java/tr/gov/turkiye/esignuidesk/view/container/MainFrame.java import tr.gov.turkiye.esignuidesk.config.Config; import javax.swing.JPanel; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tr.gov.turkiye.esignuidesk.view.container; /** * * @author iakpolat */ public class MainFrame extends javax.swing.JFrame { /** * Creates new form Main */ public MainFrame() { initComponents();
setBounds(Config.FRAME_STARTING_X, Config.FRAME_STARTING_Y, Config.FRAME_WIDTH, Config.FRAME_HEIGHT);