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 |
|---|---|---|---|---|---|---|
lvonasek/Open4speed | src/com/lvonasek/o4s/game/GameLoop.java | // Path: src/com/lvonasek/o4s/media/Settings.java
// public class Settings {
//
// public static final int MUSIC_VOLUME = 0;
// public static final int SOUND_VOLUME = 1;
// public static final int VISUAL_QUALITY = 2;
// public static final int RACE_EVENT = 3;
//
// public static final String RACE_CUSTOM_EVENT = "O4SCFG";
//
// private static int[] DEFAULT_VALUES = {100, 100, 100, 0};
//
// public static void init(Activity instance) {
// Display display = instance.getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// int level = 25 + (int) ((Math.max(size.x, size.y) - 800) / 6.4f);
// level = Math.max(0, Math.min(level, 100));
// DEFAULT_VALUES[VISUAL_QUALITY] = level;
// Log.v("Open4speed", "Default visual quality=" + level);
// }
//
// public static int getConfig(Context c, int index) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// return pref.getInt("IntCFG" + index, DEFAULT_VALUES[index]);
// }
//
// public static void setConfig(Context c, int index, int value) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = pref.edit();
// edit.putInt("IntCFG" + index, value);
// edit.commit();
// }
//
// public static String getConfig(Context c, String str) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// return pref.getString(str, "");
// }
//
// public static void setConfig(Context c, String str, String value) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = pref.edit();
// edit.putString(str, value);
// edit.commit();
// }
// }
//
// Path: src/com/lvonasek/o4s/media/Sound.java
// public class Sound {
//
// public static SoundPool snd = new SoundPool(16, AudioManager.STREAM_MUSIC, 0);
//
// public static float globalVolume = 1;
//
// int id;
// boolean loop;
// boolean playing;
// float rate;
// float volume;
//
// public Sound(String filename, boolean loop) {
// //unzip file(Android java access)
// try {
// AssetFileDescriptor afd = GameActivity.instance.getAssets().openFd(filename);
// id = snd.load(afd, 1);
// } catch (IOException e) {
// e.printStackTrace();
// this.id = -1;
// }
// this.loop = loop;
// this.rate = 1;
// this.volume = 0;
// playing = false;
// }
//
// public void play() {
// if (GameLoop.paused == 0) {
// //play sound
// if (playing)
// snd.pause(id);
// snd.play(id, volume, volume, 1, loop ? -1 : 1, rate);
// playing = true;
// }
// }
//
// /**
// * Change frequency of sound(engine, n2o)
// * @param speed is play rate(from 0.5 to 2.0)
// */
// public void setFreq(float speed) {
// //clamp rate speed
// rate = speed;
// if (speed < 0.5) {
// rate = 0.5f;
// }
// if (speed > 2.0) {
// rate = 2.0f;
// }
// }
//
// /**
// * Set sound volume
// * @param volume is sound volume(from 0 to 1)
// */
// public void setVolume(float volume) {
// //audio clip
// if (GameLoop.paused == 0) {
// volume *= 0.25f;
// this.volume = volume * globalVolume;
// }
// }
//
// /**
// * Stops playing sound
// */
// public void stop() {
// //audio clip
// if ((GameLoop.paused == 0) && playing) {
// snd.stop(id);
// playing = false;
// }
// }
// }
| import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.util.AttributeSet;
import android.view.View;
import com.lvonasek.o4s.R;
import com.lvonasek.o4s.media.Settings;
import com.lvonasek.o4s.media.Sound;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10; | sounds.add(new Sound("sfx/engineplus.ogg", true));
}
//begin
setRenderer(this);
}
/**
* Second init method - this is called when everything is ready
* @param gl OpenGL object(unused because it is for java OpenGL interpretation)
* @param config another OpenGL object(unused because it is for java OpenGL interpretation)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//check if it is first time run
if (!GameActivity.instance.init) {
//get package assets object
String apkFilePath;
ApplicationInfo appInfo;
PackageManager packMgmr = GameActivity.instance.getPackageManager();
//try to get assets
try {
appInfo = packMgmr.getApplicationInfo("com.lvonasek.o4s", 0);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
//load game
apkFilePath = appInfo.sourceDir; | // Path: src/com/lvonasek/o4s/media/Settings.java
// public class Settings {
//
// public static final int MUSIC_VOLUME = 0;
// public static final int SOUND_VOLUME = 1;
// public static final int VISUAL_QUALITY = 2;
// public static final int RACE_EVENT = 3;
//
// public static final String RACE_CUSTOM_EVENT = "O4SCFG";
//
// private static int[] DEFAULT_VALUES = {100, 100, 100, 0};
//
// public static void init(Activity instance) {
// Display display = instance.getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// int level = 25 + (int) ((Math.max(size.x, size.y) - 800) / 6.4f);
// level = Math.max(0, Math.min(level, 100));
// DEFAULT_VALUES[VISUAL_QUALITY] = level;
// Log.v("Open4speed", "Default visual quality=" + level);
// }
//
// public static int getConfig(Context c, int index) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// return pref.getInt("IntCFG" + index, DEFAULT_VALUES[index]);
// }
//
// public static void setConfig(Context c, int index, int value) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = pref.edit();
// edit.putInt("IntCFG" + index, value);
// edit.commit();
// }
//
// public static String getConfig(Context c, String str) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// return pref.getString(str, "");
// }
//
// public static void setConfig(Context c, String str, String value) {
// SharedPreferences pref = c.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
// SharedPreferences.Editor edit = pref.edit();
// edit.putString(str, value);
// edit.commit();
// }
// }
//
// Path: src/com/lvonasek/o4s/media/Sound.java
// public class Sound {
//
// public static SoundPool snd = new SoundPool(16, AudioManager.STREAM_MUSIC, 0);
//
// public static float globalVolume = 1;
//
// int id;
// boolean loop;
// boolean playing;
// float rate;
// float volume;
//
// public Sound(String filename, boolean loop) {
// //unzip file(Android java access)
// try {
// AssetFileDescriptor afd = GameActivity.instance.getAssets().openFd(filename);
// id = snd.load(afd, 1);
// } catch (IOException e) {
// e.printStackTrace();
// this.id = -1;
// }
// this.loop = loop;
// this.rate = 1;
// this.volume = 0;
// playing = false;
// }
//
// public void play() {
// if (GameLoop.paused == 0) {
// //play sound
// if (playing)
// snd.pause(id);
// snd.play(id, volume, volume, 1, loop ? -1 : 1, rate);
// playing = true;
// }
// }
//
// /**
// * Change frequency of sound(engine, n2o)
// * @param speed is play rate(from 0.5 to 2.0)
// */
// public void setFreq(float speed) {
// //clamp rate speed
// rate = speed;
// if (speed < 0.5) {
// rate = 0.5f;
// }
// if (speed > 2.0) {
// rate = 2.0f;
// }
// }
//
// /**
// * Set sound volume
// * @param volume is sound volume(from 0 to 1)
// */
// public void setVolume(float volume) {
// //audio clip
// if (GameLoop.paused == 0) {
// volume *= 0.25f;
// this.volume = volume * globalVolume;
// }
// }
//
// /**
// * Stops playing sound
// */
// public void stop() {
// //audio clip
// if ((GameLoop.paused == 0) && playing) {
// snd.stop(id);
// playing = false;
// }
// }
// }
// Path: src/com/lvonasek/o4s/game/GameLoop.java
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.util.AttributeSet;
import android.view.View;
import com.lvonasek.o4s.R;
import com.lvonasek.o4s.media.Settings;
import com.lvonasek.o4s.media.Sound;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
sounds.add(new Sound("sfx/engineplus.ogg", true));
}
//begin
setRenderer(this);
}
/**
* Second init method - this is called when everything is ready
* @param gl OpenGL object(unused because it is for java OpenGL interpretation)
* @param config another OpenGL object(unused because it is for java OpenGL interpretation)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//check if it is first time run
if (!GameActivity.instance.init) {
//get package assets object
String apkFilePath;
ApplicationInfo appInfo;
PackageManager packMgmr = GameActivity.instance.getPackageManager();
//try to get assets
try {
appInfo = packMgmr.getApplicationInfo("com.lvonasek.o4s", 0);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
//load game
apkFilePath = appInfo.sourceDir; | float quality = 0.01f * Settings.getConfig(GameActivity.instance, Settings.VISUAL_QUALITY); |
lvonasek/Open4speed | objConverter/src/ObjConverter.java | // Path: objConverter/src/geometry/Model.java
// public class Model
// {
// public ArrayList<Triangle> faces;
// public String material;
//
// public Model(String t)
// {
// faces = new ArrayList<Triangle>();
// material = t;
// }
//
// public boolean isDynamic()
// {
// return material.contains("$");
// }
//
// public AABB getAABB()
// {
// Point3D min = new Point3D(99999, 99999, 99999);
// Point3D max = new Point3D(-99999, -99999, -99999);
// for (Triangle t : faces)
// {
// if (min.x > t.a.v.x)
// min.x = t.a.v.x;
// if (min.y > t.a.v.y)
// min.y = t.a.v.y;
// if (min.z > t.a.v.z)
// min.z = t.a.v.z;
// if (max.x < t.a.v.x)
// max.x = t.a.v.x;
// if (max.y < t.a.v.y)
// max.y = t.a.v.y;
// if (max.z < t.a.v.z)
// max.z = t.a.v.z;
//
// if (min.x > t.b.v.x)
// min.x = t.b.v.x;
// if (min.y > t.b.v.y)
// min.y = t.b.v.y;
// if (min.z > t.b.v.z)
// min.z = t.b.v.z;
// if (max.x < t.b.v.x)
// max.x = t.b.v.x;
// if (max.y < t.b.v.y)
// max.y = t.b.v.y;
// if (max.z < t.b.v.z)
// max.z = t.b.v.z;
//
// if (min.x > t.c.v.x)
// min.x = t.c.v.x;
// if (min.y > t.c.v.y)
// min.y = t.c.v.y;
// if (min.z > t.c.v.z)
// min.z = t.c.v.z;
// if (max.x < t.c.v.x)
// max.x = t.c.v.x;
// if (max.y < t.c.v.y)
// max.y = t.c.v.y;
// if (max.z < t.c.v.z)
// max.z = t.c.v.z;
// }
// return new AABB(min, max);
// }
// }
| import geometry.Model;
import java.io.File;
import java.util.ArrayList;
import java.util.Map; | }
if (!ObjLoader.exists(args[0]))
{
System.err.println("Input file doesn't exist");
return;
}
// get path of output directory
String path = "";
try
{
path = args[1].substring(0, args[1].lastIndexOf('/'));
// backup old directory
new File(path).renameTo(new File("backup-" + System.currentTimeMillis()));
} catch (Exception e)
{
System.err.println("Do not put output file into converter directory");
return;
}
// create output directory
new File(path).mkdirs();
// process
long timestamp = System.currentTimeMillis();
// load data
ObjLoader obj = new ObjLoader(path);
obj.loadObj(args[0]);
obj.parseObj(args[0]);
// subdivide data | // Path: objConverter/src/geometry/Model.java
// public class Model
// {
// public ArrayList<Triangle> faces;
// public String material;
//
// public Model(String t)
// {
// faces = new ArrayList<Triangle>();
// material = t;
// }
//
// public boolean isDynamic()
// {
// return material.contains("$");
// }
//
// public AABB getAABB()
// {
// Point3D min = new Point3D(99999, 99999, 99999);
// Point3D max = new Point3D(-99999, -99999, -99999);
// for (Triangle t : faces)
// {
// if (min.x > t.a.v.x)
// min.x = t.a.v.x;
// if (min.y > t.a.v.y)
// min.y = t.a.v.y;
// if (min.z > t.a.v.z)
// min.z = t.a.v.z;
// if (max.x < t.a.v.x)
// max.x = t.a.v.x;
// if (max.y < t.a.v.y)
// max.y = t.a.v.y;
// if (max.z < t.a.v.z)
// max.z = t.a.v.z;
//
// if (min.x > t.b.v.x)
// min.x = t.b.v.x;
// if (min.y > t.b.v.y)
// min.y = t.b.v.y;
// if (min.z > t.b.v.z)
// min.z = t.b.v.z;
// if (max.x < t.b.v.x)
// max.x = t.b.v.x;
// if (max.y < t.b.v.y)
// max.y = t.b.v.y;
// if (max.z < t.b.v.z)
// max.z = t.b.v.z;
//
// if (min.x > t.c.v.x)
// min.x = t.c.v.x;
// if (min.y > t.c.v.y)
// min.y = t.c.v.y;
// if (min.z > t.c.v.z)
// min.z = t.c.v.z;
// if (max.x < t.c.v.x)
// max.x = t.c.v.x;
// if (max.y < t.c.v.y)
// max.y = t.c.v.y;
// if (max.z < t.c.v.z)
// max.z = t.c.v.z;
// }
// return new AABB(min, max);
// }
// }
// Path: objConverter/src/ObjConverter.java
import geometry.Model;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
}
if (!ObjLoader.exists(args[0]))
{
System.err.println("Input file doesn't exist");
return;
}
// get path of output directory
String path = "";
try
{
path = args[1].substring(0, args[1].lastIndexOf('/'));
// backup old directory
new File(path).renameTo(new File("backup-" + System.currentTimeMillis()));
} catch (Exception e)
{
System.err.println("Do not put output file into converter directory");
return;
}
// create output directory
new File(path).mkdirs();
// process
long timestamp = System.currentTimeMillis();
// load data
ObjLoader obj = new ObjLoader(path);
obj.loadObj(args[0]);
obj.parseObj(args[0]);
// subdivide data | Map<String, ArrayList<Model> > models = new Subdivider().subdivide(obj.getModels()); |
jbienz/FPVR | Android/FPVR/app/src/main/java/com/solersoft/fpvr/fpvrlib/Vehicle.java | // Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/util/TypeUtils.java
// public class TypeUtils
// {
// public static <T> T as(Class<T> t, Object o)
// {
// return t.isAssignableFrom(o.getClass()) ? t.cast(o) : null;
// }
// }
| import com.solersoft.fpvr.util.TypeUtils;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator; | package com.solersoft.fpvr.fpvrlib;
/**
* A base class implementation of the {@link IVehicle} interface.
*/
public abstract class Vehicle extends Connectable implements IVehicle
{
//region Constants
private static final String TAG = "Vehicle";
//endregion
//region Member Variables
private Collection<IVehicleService> services = new HashSet<IVehicleService>();
//endregion
//region Constructors
/**
* Initializes a new {@link Vehicle}.
*/
public Vehicle()
{
}
//endregion
//region Internal Methods
protected void connectService(final Iterator<IVehicleService> iterator, final boolean allConnected, final ResultHandler handler)
{
if (iterator.hasNext())
{
// Get next service
IVehicleService service = iterator.next();
// Try to get lifecycle | // Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/util/TypeUtils.java
// public class TypeUtils
// {
// public static <T> T as(Class<T> t, Object o)
// {
// return t.isAssignableFrom(o.getClass()) ? t.cast(o) : null;
// }
// }
// Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/fpvrlib/Vehicle.java
import com.solersoft.fpvr.util.TypeUtils;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
package com.solersoft.fpvr.fpvrlib;
/**
* A base class implementation of the {@link IVehicle} interface.
*/
public abstract class Vehicle extends Connectable implements IVehicle
{
//region Constants
private static final String TAG = "Vehicle";
//endregion
//region Member Variables
private Collection<IVehicleService> services = new HashSet<IVehicleService>();
//endregion
//region Constructors
/**
* Initializes a new {@link Vehicle}.
*/
public Vehicle()
{
}
//endregion
//region Internal Methods
protected void connectService(final Iterator<IVehicleService> iterator, final boolean allConnected, final ResultHandler handler)
{
if (iterator.hasNext())
{
// Get next service
IVehicleService service = iterator.next();
// Try to get lifecycle | IConnectable connectable = TypeUtils.as(IConnectable.class, service); |
jbienz/FPVR | Android/FPVR/app/src/main/java/com/solersoft/fpvr/fpvrdji/DJIGimbalService.java | // Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/util/DJI.java
// public class DJI
// {
// /**
// * Returns true if the result is considered a success.
// * @param errorCode the result.
// * @return true if result is a success; otherwise false.
// */
// public static boolean Success(int errorCode)
// {
// return errorCode == 0;
// }
// }
| import android.util.Log;
import com.solersoft.fpvr.fpvrlib.*;
import com.solersoft.fpvr.util.DJI;
import java.security.InvalidParameterException;
import java.util.Timer;
import java.util.TimerTask;
import dji.sdk.api.DJIDrone;
import dji.sdk.api.DJIError;
import dji.sdk.api.Gimbal.DJIGimbal;
import dji.sdk.api.Gimbal.DJIGimbalAttitude;
import dji.sdk.api.Gimbal.DJIGimbalCapacity;
import dji.sdk.api.Gimbal.DJIGimbalRotation;
import dji.sdk.interfaces.DJIExecuteResultCallback;
import dji.sdk.interfaces.DJIGimbalUpdateAttitudeCallBack; | yaw = clampYaw(yaw);
// Scale
int ps = (int)Math.round(pitch);
int rs = (int)Math.round(roll);
int ys = (int)Math.round(yaw);
boolean enabled = true;
boolean directionBackward = false;
DJIGimbalRotation pr = new DJIGimbalRotation(enabled, directionBackward, relative, ps);
DJIGimbalRotation rr = new DJIGimbalRotation(enabled, directionBackward, relative, rs);
DJIGimbalRotation yr = new DJIGimbalRotation(enabled, directionBackward, relative, ys);
// Move the gimbal
Log.i(TAG, "Native Move: PS: " + ps + " RS: " + rs + " YS: " + ys);
DJIDrone.getDjiGimbal().updateGimbalAttitude(pr, rr, yr);
}
private void setGimbalSpeed(int pitchSpeed, int rollSpeed, int yawSpeed)
{
// Make sure enabled
if (!isEnabled()) { return; }
// Set Gimbal Move Speed
Log.i(TAG, "Updating gimbal speed: P: " + pitchSpeed + " R: " + rollSpeed + " Y: " + yawSpeed);
DJIDrone.getDjiRemoteController().setGimbalControlSpeed(pitchSpeed, rollSpeed, yawSpeed, new DJIExecuteResultCallback()
{
@Override
public void onResult(DJIError djiError)
{ | // Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/util/DJI.java
// public class DJI
// {
// /**
// * Returns true if the result is considered a success.
// * @param errorCode the result.
// * @return true if result is a success; otherwise false.
// */
// public static boolean Success(int errorCode)
// {
// return errorCode == 0;
// }
// }
// Path: Android/FPVR/app/src/main/java/com/solersoft/fpvr/fpvrdji/DJIGimbalService.java
import android.util.Log;
import com.solersoft.fpvr.fpvrlib.*;
import com.solersoft.fpvr.util.DJI;
import java.security.InvalidParameterException;
import java.util.Timer;
import java.util.TimerTask;
import dji.sdk.api.DJIDrone;
import dji.sdk.api.DJIError;
import dji.sdk.api.Gimbal.DJIGimbal;
import dji.sdk.api.Gimbal.DJIGimbalAttitude;
import dji.sdk.api.Gimbal.DJIGimbalCapacity;
import dji.sdk.api.Gimbal.DJIGimbalRotation;
import dji.sdk.interfaces.DJIExecuteResultCallback;
import dji.sdk.interfaces.DJIGimbalUpdateAttitudeCallBack;
yaw = clampYaw(yaw);
// Scale
int ps = (int)Math.round(pitch);
int rs = (int)Math.round(roll);
int ys = (int)Math.round(yaw);
boolean enabled = true;
boolean directionBackward = false;
DJIGimbalRotation pr = new DJIGimbalRotation(enabled, directionBackward, relative, ps);
DJIGimbalRotation rr = new DJIGimbalRotation(enabled, directionBackward, relative, rs);
DJIGimbalRotation yr = new DJIGimbalRotation(enabled, directionBackward, relative, ys);
// Move the gimbal
Log.i(TAG, "Native Move: PS: " + ps + " RS: " + rs + " YS: " + ys);
DJIDrone.getDjiGimbal().updateGimbalAttitude(pr, rr, yr);
}
private void setGimbalSpeed(int pitchSpeed, int rollSpeed, int yawSpeed)
{
// Make sure enabled
if (!isEnabled()) { return; }
// Set Gimbal Move Speed
Log.i(TAG, "Updating gimbal speed: P: " + pitchSpeed + " R: " + rollSpeed + " Y: " + yawSpeed);
DJIDrone.getDjiRemoteController().setGimbalControlSpeed(pitchSpeed, rollSpeed, yawSpeed, new DJIExecuteResultCallback()
{
@Override
public void onResult(DJIError djiError)
{ | if (!DJI.Success(djiError.errorCode)) |
kstenschke/referencer-plugin | src/com/kstenschke/referencer/referencers/insertOrCopy/InsertOrCopyReferencerFilesFolders.java | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.kstenschke.referencer.resources.StaticTexts;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.referencers.insertOrCopy;
class InsertOrCopyReferencerFilesFolders {
/**
* Get items regarding files / folder / paths
*
* @param e Action system event
* @return List of PHP items
*/
public static List<String> getReferenceItems(AnActionEvent e) {
List<String> referenceItems = new ArrayList<>();
final Project project = e.getData(PlatformDataKeys.PROJECT);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if (project == null || editor == null) {
return referenceItems;
}
final Document document = editor.getDocument();
/* Get line number the caret is in */
int caretOffset = editor.getCaretModel().getOffset();
int lineNumber = document.getLineNumber(caretOffset);
/* File path and name */
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
String filePath = file != null ? file.getPath() : "";
String filename = file != null ? file.getName() : "";
/* Add items */
FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
int amountOpenFiles = fileEditorManager.getOpenFiles().length;
if (amountOpenFiles > 1) { | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
// Path: src/com/kstenschke/referencer/referencers/insertOrCopy/InsertOrCopyReferencerFilesFolders.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.kstenschke.referencer.resources.StaticTexts;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.referencers.insertOrCopy;
class InsertOrCopyReferencerFilesFolders {
/**
* Get items regarding files / folder / paths
*
* @param e Action system event
* @return List of PHP items
*/
public static List<String> getReferenceItems(AnActionEvent e) {
List<String> referenceItems = new ArrayList<>();
final Project project = e.getData(PlatformDataKeys.PROJECT);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if (project == null || editor == null) {
return referenceItems;
}
final Document document = editor.getDocument();
/* Get line number the caret is in */
int caretOffset = editor.getCaretModel().getOffset();
int lineNumber = document.getLineNumber(caretOffset);
/* File path and name */
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
String filePath = file != null ? file.getPath() : "";
String filename = file != null ? file.getName() : "";
/* Add items */
FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
int amountOpenFiles = fileEditorManager.getOpenFiles().length;
if (amountOpenFiles > 1) { | referenceItems.add(StaticTexts.POPUP_ITEM_OPEN_FILES); |
kstenschke/referencer-plugin | src/com/kstenschke/referencer/resources/ui/PopupContextGo.java | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
| import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.kstenschke.referencer.resources.StaticTexts;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List; | /*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.resources.ui;
public class PopupContextGo {
private final JPopupMenu popup;
public PopupContextGo(final Project curProject) {
this.popup = new JPopupMenu();
/* Remove all bookmarks from current file */ | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
// Path: src/com/kstenschke/referencer/resources/ui/PopupContextGo.java
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.kstenschke.referencer.resources.StaticTexts;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
/*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.resources.ui;
public class PopupContextGo {
private final JPopupMenu popup;
public PopupContextGo(final Project curProject) {
this.popup = new JPopupMenu();
/* Remove all bookmarks from current file */ | JMenuItem menuItemSelectedBookmarkAdd = new JMenuItem(StaticTexts.POPUP_GO_REMOVE_ALL_BOOKMARKS); |
kstenschke/referencer-plugin | src/com/kstenschke/referencer/resources/ui/DividedListCellRenderer.java | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
| import com.intellij.ui.Gray;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.util.ui.UIUtil;
import com.kstenschke.referencer.resources.StaticTexts;
import javax.swing.*;
import java.awt.*; | /*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.resources.ui;
/**
* List cell renderer with a separator, items with "_" as text are displayed as separators dividing item groups
*/
public class DividedListCellRenderer extends DefaultListCellRenderer {
private final Font separatorFont;
private final Color separatorColorBackground;
private final Color separatorColorForeground;
public DividedListCellRenderer(JBList<Object> list) {
boolean isUnderDarcula = UIUtil.isUnderDarcula();
Font defaultFont = list.getFont();
this.separatorFont = new Font(defaultFont.getName(), defaultFont.getStyle(), defaultFont.getSize());
this.separatorColorBackground = isUnderDarcula ? Gray._79 : Gray._243;
this.separatorColorForeground = isUnderDarcula ? Gray._250 : Gray._79;
}
/**
* @return The rendered cell
* @param list List of reference items
* @param value Value of reference item
* @param index Item index
* @param isSelected Item currently selected?
* @param cellHasFocus Item currently has focus?
*/
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
String valueStr = null;
if (value != null) {
valueStr = value.toString();
valueStr = valueStr.substring(valueStr.indexOf("=>") + 2); /* Do not output item index prefix */
/* Apply section title styling */ | // Path: src/com/kstenschke/referencer/resources/StaticTexts.java
// public class StaticTexts {
//
// @NonNls public static final String SETTINGS_DISPLAY_NAME = "Referencer";
//
// /* Popup titles */
// @NonNls public static final String POPUP_TITLE_ACTION_COPY = "Select what to copy";
// @NonNls public static final String POPUP_TITLE_ACTION_INSERT = "Select Insertion";
// @NonNls public static final String POPUP_TITLE_ACTION_GO = "Select where to go";
// @NonNls public static final String POPUP_TITLE_ACTION_GO_FUNNY = "Where do you want to go today?";
//
// /* Popup items */
// @NonNls public static final String POPUP_ITEM_METHODS_IN_FILE = "List of methods in current file";
// public static final String POPUP_ITEM_OPEN_FILES = "List of currently opened files";
//
// /* Popup section titles */
// @NonNls public static final String POPUP_ITEM_PREFIX_SECTION_TITLE = "SECTIONTITLE:";
//
// @NonNls public static final String POPUP_SECTION_BOOKMARKS = "SECTIONTITLE: Bookmarks";
// @NonNls public static final String POPUP_SECTION_FUNCTIONS = "SECTIONTITLE: Methods";
// @NonNls public static final String POPUP_SECTION_REGIONS = "SECTIONTITLE: Regions";
// @NonNls public static final String POPUP_SECTION_TITLE_DATE_TIME = "SECTIONTITLE: Date / Time";
// @NonNls public static final String POPUP_SECTION_TITLE_FILES_PATHS = "SECTIONTITLE: Files / Paths";
// @NonNls public static final String POPUP_SECTION_TITLE_JAVASCRIPT = "SECTIONTITLE: JavaScript";
// @NonNls public static final String POPUP_SECTION_TITLE_MARKDOWN = "SECTIONTITLE: Markdown";
// @NonNls public static final String POPUP_SECTION_TITLE_PHP = "SECTIONTITLE: PHP";
// @NonNls public static final String POPUP_SECTION_TITLE_TEXT_COMPLETIONS = "SECTIONTITLE: Text Completions";
//
// /* Go action context menu */
// @NonNls public static final String POPUP_GO_REMOVE_ALL_BOOKMARKS = "Remove all Bookmarks from this File";
//
// /* Notifications */
// @NonNls public static final String NOTIFY_GOTO_NONE_FOUND = "No GoTo destinations found";
// @NonNls public static final String NOTIFY_NO_PROJECT_OPEN = "A project must be loaded before using this option";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_DOESNT_EXIST = "No referencer_patterns.txt found";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_FAILED_SAVE = "Failed saving referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_NO_REPLACE_PATTERNS = "No search/replace patterns";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_LOADED = "Imported settings from referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REFERENCER_TXT_SAVED = "Exported settings to referencer_patterns.txt";
// @NonNls public static final String NOTIFY_REPLACE_NONE_CONFIGURED = "No replace patterns configured";
// }
// Path: src/com/kstenschke/referencer/resources/ui/DividedListCellRenderer.java
import com.intellij.ui.Gray;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.util.ui.UIUtil;
import com.kstenschke.referencer.resources.StaticTexts;
import javax.swing.*;
import java.awt.*;
/*
* Copyright Kay Stenschke
*
* 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.kstenschke.referencer.resources.ui;
/**
* List cell renderer with a separator, items with "_" as text are displayed as separators dividing item groups
*/
public class DividedListCellRenderer extends DefaultListCellRenderer {
private final Font separatorFont;
private final Color separatorColorBackground;
private final Color separatorColorForeground;
public DividedListCellRenderer(JBList<Object> list) {
boolean isUnderDarcula = UIUtil.isUnderDarcula();
Font defaultFont = list.getFont();
this.separatorFont = new Font(defaultFont.getName(), defaultFont.getStyle(), defaultFont.getSize());
this.separatorColorBackground = isUnderDarcula ? Gray._79 : Gray._243;
this.separatorColorForeground = isUnderDarcula ? Gray._250 : Gray._79;
}
/**
* @return The rendered cell
* @param list List of reference items
* @param value Value of reference item
* @param index Item index
* @param isSelected Item currently selected?
* @param cellHasFocus Item currently has focus?
*/
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
String valueStr = null;
if (value != null) {
valueStr = value.toString();
valueStr = valueStr.substring(valueStr.indexOf("=>") + 2); /* Do not output item index prefix */
/* Apply section title styling */ | if (valueStr.startsWith(StaticTexts.POPUP_ITEM_PREFIX_SECTION_TITLE)) { |
mozack/abra2 | src/main/java/abra/IndelShifter.java | // Path: src/main/java/abra/Logger.java
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import abra.Logger.Level;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.TextCigarCodec; | Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
chromosome, subCigar, subSeq, c2r);
//TODO: Merge abutting indels if applicable
elems.set(i-1, newCigar.getCigarElement(0));
elems.set(i, newCigar.getCigarElement(1));
if (newCigar.getCigarElements().size() == 3) {
elems.set(i+1, newCigar.getCigarElement(2));
} else {
elems.remove(i+1);
elemSize -= 1;
}
}
}
mergeAbuttingElements(elems);
return new Cigar(elems);
} catch (RuntimeException e) {
e.printStackTrace();
Logger.error("Error on: " + refStart + ", " + refEnd + "," + chromosome + ", " + cigar + ", " + seq);
throw e;
}
}
// Merge neighboring Cigar elements of same type
// mutates input
private void mergeAbuttingElements(List<CigarElement> elems) {
int origSize = elems.size(); | // Path: src/main/java/abra/Logger.java
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
// Path: src/main/java/abra/IndelShifter.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import abra.Logger.Level;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.TextCigarCodec;
Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
chromosome, subCigar, subSeq, c2r);
//TODO: Merge abutting indels if applicable
elems.set(i-1, newCigar.getCigarElement(0));
elems.set(i, newCigar.getCigarElement(1));
if (newCigar.getCigarElements().size() == 3) {
elems.set(i+1, newCigar.getCigarElement(2));
} else {
elems.remove(i+1);
elemSize -= 1;
}
}
}
mergeAbuttingElements(elems);
return new Cigar(elems);
} catch (RuntimeException e) {
e.printStackTrace();
Logger.error("Error on: " + refStart + ", " + refEnd + "," + chromosome + ", " + cigar + ", " + seq);
throw e;
}
}
// Merge neighboring Cigar elements of same type
// mutates input
private void mergeAbuttingElements(List<CigarElement> elems) {
int origSize = elems.size(); | List<CigarElement> orig = Logger.LEVEL == Level.TRACE ? new ArrayList<CigarElement>(elems) : null; |
mozack/abra2 | src/main/java/abra/AltContigGenerator.java | // Path: src/main/java/abra/SAMRecordUtils.java
// public static class ReadBlock {
// private int readPos;
// private int refPos;
// private int length;
// private CigarElement elem;
//
// public ReadBlock(int readPos, int refPos, int length, CigarElement elem) {
// this.readPos = readPos;
// this.refPos = refPos;
// this.length = length;
// this.elem = elem;
// }
//
// public int getReadPos() {
// return readPos;
// }
//
// public int getRefPos() {
// return refPos;
// }
//
// public int getLength() {
// return length;
// }
//
// public CigarElement getCigarElement() {
// return elem;
// }
// }
| import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.SAMRecordUtils.ReadBlock; | elems.get(0).getOperator() == CigarOperator.M &&
elems.get(2).getOperator() == CigarOperator.M &&
(elems.get(1).getOperator() == CigarOperator.D || elems.get(1).getOperator() == CigarOperator.I)) {
String insertBases = null;
char type = '0';
if (elems.get(1).getOperator() == CigarOperator.D) {
type = 'D';
} else if (elems.get(1).getOperator() == CigarOperator.I) {
type = 'I';
int start = elems.get(0).getLength();
int stop = start + elems.get(1).getLength();
insertBases = read.getReadString().substring(start, stop);
}
int refStart = read.getAlignmentStart() + elems.get(0).getLength();
// Require indel start to be within region
if (refStart >= region.getStart() && refStart <= region.getEnd()) {
Indel indel = new Indel(type, read.getReferenceName(), refStart, elems.get(1).getLength(), insertBases, elems.get(0).getLength(), SAMRecordUtils.sumBaseQuals(read));
if (indels.containsKey(indel)) {
indels.get(indel).addReadPosition(elems.get(0).getLength(), SAMRecordUtils.sumBaseQuals(read));
} else {
indels.put(indel, indel);
}
}
} else if(SAMRecordUtils.getNumGaps(read) > 1) {
// Handle read containing multiple indels (create single contig)
List<Indel> indelComponents = new ArrayList<Indel>(); | // Path: src/main/java/abra/SAMRecordUtils.java
// public static class ReadBlock {
// private int readPos;
// private int refPos;
// private int length;
// private CigarElement elem;
//
// public ReadBlock(int readPos, int refPos, int length, CigarElement elem) {
// this.readPos = readPos;
// this.refPos = refPos;
// this.length = length;
// this.elem = elem;
// }
//
// public int getReadPos() {
// return readPos;
// }
//
// public int getRefPos() {
// return refPos;
// }
//
// public int getLength() {
// return length;
// }
//
// public CigarElement getCigarElement() {
// return elem;
// }
// }
// Path: src/main/java/abra/AltContigGenerator.java
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.SAMRecordUtils.ReadBlock;
elems.get(0).getOperator() == CigarOperator.M &&
elems.get(2).getOperator() == CigarOperator.M &&
(elems.get(1).getOperator() == CigarOperator.D || elems.get(1).getOperator() == CigarOperator.I)) {
String insertBases = null;
char type = '0';
if (elems.get(1).getOperator() == CigarOperator.D) {
type = 'D';
} else if (elems.get(1).getOperator() == CigarOperator.I) {
type = 'I';
int start = elems.get(0).getLength();
int stop = start + elems.get(1).getLength();
insertBases = read.getReadString().substring(start, stop);
}
int refStart = read.getAlignmentStart() + elems.get(0).getLength();
// Require indel start to be within region
if (refStart >= region.getStart() && refStart <= region.getEnd()) {
Indel indel = new Indel(type, read.getReferenceName(), refStart, elems.get(1).getLength(), insertBases, elems.get(0).getLength(), SAMRecordUtils.sumBaseQuals(read));
if (indels.containsKey(indel)) {
indels.get(indel).addReadPosition(elems.get(0).getLength(), SAMRecordUtils.sumBaseQuals(read));
} else {
indels.put(indel, indel);
}
}
} else if(SAMRecordUtils.getNumGaps(read) > 1) {
// Handle read containing multiple indels (create single contig)
List<Indel> indelComponents = new ArrayList<Indel>(); | List<ReadBlock> readBlocks = SAMRecordUtils.getReadBlocks(read.getCigar(), read.getAlignmentStart()); |
mozack/abra2 | src/main/java/abra/cadabra/CadabraOptions.java | // Path: src/main/java/abra/Logger.java
// public class Logger {
//
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
//
// public static Level LEVEL = Level.INFO;
//
// private static Map<String, Level> stringToLevel;
//
// static {
// stringToLevel = new HashMap<String, Level>();
// stringToLevel.put("TRACE", Level.TRACE);
// stringToLevel.put("DEBUG", Level.DEBUG);
// stringToLevel.put("INFO", Level.INFO);
// stringToLevel.put("WARN", Level.WARN);
// stringToLevel.put("ERROR", Level.ERROR);
// }
//
// // For trace or debug messages, use varargs to avoid string concatenation unless enabled
//
// public static void trace(String format, Object... args) {
// if (LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.TRACE);
// }
// }
//
// public static void debug(String format, Object... args) {
// if (LEVEL == Level.DEBUG || LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.DEBUG);
// }
// }
//
// public static void info(String format, Object... args) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO) {
// log(String.format(format, args), Level.INFO);
// }
// }
//
// public static void warn(String message) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO || LEVEL == Level.WARN) {
// log(message, Level.WARN);
// }
// }
//
// public static void error(String message) {
// log(message, Level.ERROR);
// }
//
// public static void setLevel(String str) {
// Level level = stringToLevel.get(str.toUpperCase());
// if (level == null) {
// throw new IllegalArgumentException("Log level must be one of trace, debug, info, warn or error.");
// }
//
// Logger.LEVEL = level;
// }
//
// public static void log(String message, Level level) {
//
// String levelStr = "UNKNOWN";
//
// switch (level) {
// case ERROR:
// levelStr = "ERROR";
// break;
// case WARN:
// levelStr = "WARNING";
// break;
// case INFO:
// levelStr = "INFO";
// break;
// case DEBUG:
// levelStr = "DEBUG";
// break;
// case TRACE:
// levelStr = "TRACE";
// break;
// }
//
// System.err.println(levelStr + "\t" + new Date() + "\t" + message);
// }
// }
//
// Path: src/main/java/abra/Options.java
// public abstract class Options {
// protected static final String HELP = "help";
//
// private OptionSet options;
//
// protected void printHelp() {
// try {
// getOptionParser().printHelpOn(System.err);
// }
// catch (IOException e) {
// e.printStackTrace();
// throw new RuntimeException("IOException encountered when attempting to output help.");
// }
// }
//
// public void parseOptions(String[] args) {
//
// try {
// options = getOptionParser().parse(args);
//
// if (options.has(HELP)) {
// printHelp();
// } else {
// init();
// validate();
// }
// } catch (joptsimple.OptionException e) {
// System.err.println(e.getMessage());
// printHelp();
// throw e;
// }
// }
//
// protected OptionSet getOptions() {
// return options;
// }
//
// abstract protected OptionParser getOptionParser();
//
// abstract protected void validate();
//
// protected void init() {
// }
// }
| import abra.Logger;
import abra.Options;
import joptsimple.OptionParser; | return parser;
}
public void init() {
this.numThreads = (Integer) getOptions().valueOf(NUM_THREADS);
this.tumor = (String) getOptions().valueOf(TUMOR);
if (tumor == null) {
this.tumor = (String) getOptions().valueOf(SAMPLE);
}
this.normal = (String) getOptions().valueOf(NORMAL);
this.reference = (String) getOptions().valueOf(REFERENCE);
this.strpThreshold = (Integer) getOptions().valueOf(STRP_THRESHOLD);
this.hrunThreshold = (Integer) getOptions().valueOf(HRUN_THRESHOLD);
this.ispanFilter = (Integer) getOptions().valueOf(ISPAN_FILTER);
this.qualFilter = (Float) getOptions().valueOf(QUAL_FILTER);
this.fsFilter = (Integer) getOptions().valueOf(FS_FILTER);
this.lowMQFilter = (Float) getOptions().valueOf(LOW_MQ_FILTER);
this.minQual = (Float) getOptions().valueOf(MIN_QUAL);
this.minMapq = (Integer) getOptions().valueOf(MIN_MAPQ);
this.minVaf = (Float) getOptions().valueOf(MIN_VAF);
this.pcrPenalty = (Integer) getOptions().valueOf(PCR_PENALTY);
this.oddsr = (Float) getOptions().valueOf(ODDS_RATIO);
}
@Override
protected void validate() {
isValid = true;
if (tumor == null) { | // Path: src/main/java/abra/Logger.java
// public class Logger {
//
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
//
// public static Level LEVEL = Level.INFO;
//
// private static Map<String, Level> stringToLevel;
//
// static {
// stringToLevel = new HashMap<String, Level>();
// stringToLevel.put("TRACE", Level.TRACE);
// stringToLevel.put("DEBUG", Level.DEBUG);
// stringToLevel.put("INFO", Level.INFO);
// stringToLevel.put("WARN", Level.WARN);
// stringToLevel.put("ERROR", Level.ERROR);
// }
//
// // For trace or debug messages, use varargs to avoid string concatenation unless enabled
//
// public static void trace(String format, Object... args) {
// if (LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.TRACE);
// }
// }
//
// public static void debug(String format, Object... args) {
// if (LEVEL == Level.DEBUG || LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.DEBUG);
// }
// }
//
// public static void info(String format, Object... args) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO) {
// log(String.format(format, args), Level.INFO);
// }
// }
//
// public static void warn(String message) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO || LEVEL == Level.WARN) {
// log(message, Level.WARN);
// }
// }
//
// public static void error(String message) {
// log(message, Level.ERROR);
// }
//
// public static void setLevel(String str) {
// Level level = stringToLevel.get(str.toUpperCase());
// if (level == null) {
// throw new IllegalArgumentException("Log level must be one of trace, debug, info, warn or error.");
// }
//
// Logger.LEVEL = level;
// }
//
// public static void log(String message, Level level) {
//
// String levelStr = "UNKNOWN";
//
// switch (level) {
// case ERROR:
// levelStr = "ERROR";
// break;
// case WARN:
// levelStr = "WARNING";
// break;
// case INFO:
// levelStr = "INFO";
// break;
// case DEBUG:
// levelStr = "DEBUG";
// break;
// case TRACE:
// levelStr = "TRACE";
// break;
// }
//
// System.err.println(levelStr + "\t" + new Date() + "\t" + message);
// }
// }
//
// Path: src/main/java/abra/Options.java
// public abstract class Options {
// protected static final String HELP = "help";
//
// private OptionSet options;
//
// protected void printHelp() {
// try {
// getOptionParser().printHelpOn(System.err);
// }
// catch (IOException e) {
// e.printStackTrace();
// throw new RuntimeException("IOException encountered when attempting to output help.");
// }
// }
//
// public void parseOptions(String[] args) {
//
// try {
// options = getOptionParser().parse(args);
//
// if (options.has(HELP)) {
// printHelp();
// } else {
// init();
// validate();
// }
// } catch (joptsimple.OptionException e) {
// System.err.println(e.getMessage());
// printHelp();
// throw e;
// }
// }
//
// protected OptionSet getOptions() {
// return options;
// }
//
// abstract protected OptionParser getOptionParser();
//
// abstract protected void validate();
//
// protected void init() {
// }
// }
// Path: src/main/java/abra/cadabra/CadabraOptions.java
import abra.Logger;
import abra.Options;
import joptsimple.OptionParser;
return parser;
}
public void init() {
this.numThreads = (Integer) getOptions().valueOf(NUM_THREADS);
this.tumor = (String) getOptions().valueOf(TUMOR);
if (tumor == null) {
this.tumor = (String) getOptions().valueOf(SAMPLE);
}
this.normal = (String) getOptions().valueOf(NORMAL);
this.reference = (String) getOptions().valueOf(REFERENCE);
this.strpThreshold = (Integer) getOptions().valueOf(STRP_THRESHOLD);
this.hrunThreshold = (Integer) getOptions().valueOf(HRUN_THRESHOLD);
this.ispanFilter = (Integer) getOptions().valueOf(ISPAN_FILTER);
this.qualFilter = (Float) getOptions().valueOf(QUAL_FILTER);
this.fsFilter = (Integer) getOptions().valueOf(FS_FILTER);
this.lowMQFilter = (Float) getOptions().valueOf(LOW_MQ_FILTER);
this.minQual = (Float) getOptions().valueOf(MIN_QUAL);
this.minMapq = (Integer) getOptions().valueOf(MIN_MAPQ);
this.minVaf = (Float) getOptions().valueOf(MIN_VAF);
this.pcrPenalty = (Integer) getOptions().valueOf(PCR_PENALTY);
this.oddsr = (Float) getOptions().valueOf(ODDS_RATIO);
}
@Override
protected void validate() {
isValid = true;
if (tumor == null) { | Logger.error("Please specify a " + TUMOR + " or a " + SAMPLE); |
mozack/abra2 | src/main/java/abra/NativeSemiGlobalAligner.java | // Path: src/main/java/abra/SemiGlobalAligner.java
// static class Result {
// Result(int score, int secondBest, int position, int endPosition, String cigar) {
// this.score = score;
// this.secondBest = secondBest;
// this.position = position;
// this.endPosition = endPosition;
// this.cigar = cigar;
// }
//
// int score;
// int secondBest;
// int position;
// int endPosition;
// String cigar;
//
// public String toString() {
// return String.format("score: %d, secondBest: %d, pos: %d, endPos: %d, cigar: %s", score, secondBest, position, endPosition, cigar);
// }
// }
| import abra.SemiGlobalAligner.Result; | package abra;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
public static final int MAX_CONTIG_LEN = 1998;
public static final int MAX_REF_LEN = 4998;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
| // Path: src/main/java/abra/SemiGlobalAligner.java
// static class Result {
// Result(int score, int secondBest, int position, int endPosition, String cigar) {
// this.score = score;
// this.secondBest = secondBest;
// this.position = position;
// this.endPosition = endPosition;
// this.cigar = cigar;
// }
//
// int score;
// int secondBest;
// int position;
// int endPosition;
// String cigar;
//
// public String toString() {
// return String.format("score: %d, secondBest: %d, pos: %d, endPos: %d, cigar: %s", score, secondBest, position, endPosition, cigar);
// }
// }
// Path: src/main/java/abra/NativeSemiGlobalAligner.java
import abra.SemiGlobalAligner.Result;
package abra;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
public static final int MAX_CONTIG_LEN = 1998;
public static final int MAX_REF_LEN = 4998;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
| public Result align(String seq1, String seq2) { |
mozack/abra2 | src/test/java/abra/CigarUtilsTest.java | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
| import static org.testng.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment; | String newCigar = CigarUtils.extendCigarWithMatches(cigar, 10, 15);
assertEquals(newCigar, "60M10D65M");
cigar = "100M";
newCigar = CigarUtils.extendCigarWithMatches(cigar, 10, 15);
assertEquals(newCigar, "125M");
}
@Test (groups = "unit")
public void testInjectSplice() {
String cigar = "90M5I5D205M";
int junctionPos = 100;
int junctionLength = 2000;
String newCigar = CigarUtils.injectSplice(cigar, junctionPos, junctionLength);
assertEquals(newCigar, "90M5I5D5M2000N200M");
}
@Test (groups = "unit")
public void testInjectSplices() {
String cigar = "90M5I5D205M";
List<Integer> junctionPos = Arrays.asList(100, 125);
List<Integer> junctionLength = Arrays.asList(2000, 50000);
String newCigar = CigarUtils.injectSplices(cigar, junctionPos, junctionLength);
assertEquals(newCigar, "90M5I5D5M2000N25M50000N175M");
}
private int testEquivalenceAndSelectIntronPreferred(String cigar1, String cigar2) { | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
// Path: src/test/java/abra/CigarUtilsTest.java
import static org.testng.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment;
String newCigar = CigarUtils.extendCigarWithMatches(cigar, 10, 15);
assertEquals(newCigar, "60M10D65M");
cigar = "100M";
newCigar = CigarUtils.extendCigarWithMatches(cigar, 10, 15);
assertEquals(newCigar, "125M");
}
@Test (groups = "unit")
public void testInjectSplice() {
String cigar = "90M5I5D205M";
int junctionPos = 100;
int junctionLength = 2000;
String newCigar = CigarUtils.injectSplice(cigar, junctionPos, junctionLength);
assertEquals(newCigar, "90M5I5D5M2000N200M");
}
@Test (groups = "unit")
public void testInjectSplices() {
String cigar = "90M5I5D205M";
List<Integer> junctionPos = Arrays.asList(100, 125);
List<Integer> junctionLength = Arrays.asList(2000, 50000);
String newCigar = CigarUtils.injectSplices(cigar, junctionPos, junctionLength);
assertEquals(newCigar, "90M5I5D5M2000N25M50000N175M");
}
private int testEquivalenceAndSelectIntronPreferred(String cigar1, String cigar2) { | Alignment a1 = new Alignment(); |
mozack/abra2 | src/main/java/abra/CigarUtils.java | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import abra.ReadEvaluator.Alignment; | newBlocks.add(new CigarBlock(blockLen1, block.type));
newBlocks.add(new CigarBlock(junctionLength, 'N'));
if (blockLen2 > 0) {
newBlocks.add(new CigarBlock(blockLen2, block.type));
}
refPos += block.length;
} else {
newBlocks.add(block);
refPos += block.length;
}
} else {
// Do not advance ref pos for insertions or introns
newBlocks.add(block);
}
}
return cigarStringFromCigarBlocks(newBlocks);
}
// Assumes input junctions are sorted by coordinate
public static String injectSplices(String cigar, List<Integer> junctionPos, List<Integer> junctionLength) {
for (int i=0; i<junctionPos.size(); i++) {
cigar = injectSplice(cigar, junctionPos.get(i), junctionLength.get(i));
}
return cigar;
}
| // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
// Path: src/main/java/abra/CigarUtils.java
import java.util.ArrayList;
import java.util.List;
import abra.ReadEvaluator.Alignment;
newBlocks.add(new CigarBlock(blockLen1, block.type));
newBlocks.add(new CigarBlock(junctionLength, 'N'));
if (blockLen2 > 0) {
newBlocks.add(new CigarBlock(blockLen2, block.type));
}
refPos += block.length;
} else {
newBlocks.add(block);
refPos += block.length;
}
} else {
// Do not advance ref pos for insertions or introns
newBlocks.add(block);
}
}
return cigarStringFromCigarBlocks(newBlocks);
}
// Assumes input junctions are sorted by coordinate
public static String injectSplices(String cigar, List<Integer> junctionPos, List<Integer> junctionLength) {
for (int i=0; i<junctionPos.size(); i++) {
cigar = injectSplice(cigar, junctionPos.get(i), junctionLength.get(i));
}
return cigar;
}
| private static int selectPrimaryAlignment(Alignment alignment1, Alignment alignment2, int def) { |
mozack/abra2 | src/test/java/abra/SimpleMapperTest.java | // Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
| import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult; | package abra;
public class SimpleMapperTest {
private String contig1 = "TTCAACTAGAGAGAGGTAAAAATTTTTCTAGAACATGAATTGCCCACTCCCCTCATTCCTTCTCAGAAACTAACTGAATTCCAGTGGGTGTGCCTGGCAAACCCAAAAGCAGTTTCTGTTCAGGATGCTGGTCTTACCTGTGAAGGCGTTCATGAACGTGGAGAGGGACCGGTTCAACATTTTGAAGAAAGGGTCTCTGCACGGATATTTCTGAGACCCACAAAGGACGGTATGCTCAAGAATGTGAGGAACACCAGTACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTGCTGCGGACACAGTTCCCAGATGCATCATCACCTCAGGCTACTAGAAATCATCATTCTGACACCACAATCCTCCAGCACAGGGTTTTCCAACTATA";
private String contig2 = "ATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGAT";
private static final double DEFAULT_MISMATCH_RATE = .05;
@Test (groups = "unit" )
public void testMapExact() {
SimpleMapper sm = new SimpleMapper(contig1, DEFAULT_MISMATCH_RATE);
String read = "TACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTG"; | // Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
// Path: src/test/java/abra/SimpleMapperTest.java
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult;
package abra;
public class SimpleMapperTest {
private String contig1 = "TTCAACTAGAGAGAGGTAAAAATTTTTCTAGAACATGAATTGCCCACTCCCCTCATTCCTTCTCAGAAACTAACTGAATTCCAGTGGGTGTGCCTGGCAAACCCAAAAGCAGTTTCTGTTCAGGATGCTGGTCTTACCTGTGAAGGCGTTCATGAACGTGGAGAGGGACCGGTTCAACATTTTGAAGAAAGGGTCTCTGCACGGATATTTCTGAGACCCACAAAGGACGGTATGCTCAAGAATGTGAGGAACACCAGTACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTGCTGCGGACACAGTTCCCAGATGCATCATCACCTCAGGCTACTAGAAATCATCATTCTGACACCACAATCCTCCAGCACAGGGTTTTCCAACTATA";
private String contig2 = "ATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGAT";
private static final double DEFAULT_MISMATCH_RATE = .05;
@Test (groups = "unit" )
public void testMapExact() {
SimpleMapper sm = new SimpleMapper(contig1, DEFAULT_MISMATCH_RATE);
String read = "TACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTG"; | SimpleMapperResult smr = sm.map(read); |
mozack/abra2 | src/test/java/abra/SimpleMapperTest.java | // Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
| import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult; | package abra;
public class SimpleMapperTest {
private String contig1 = "TTCAACTAGAGAGAGGTAAAAATTTTTCTAGAACATGAATTGCCCACTCCCCTCATTCCTTCTCAGAAACTAACTGAATTCCAGTGGGTGTGCCTGGCAAACCCAAAAGCAGTTTCTGTTCAGGATGCTGGTCTTACCTGTGAAGGCGTTCATGAACGTGGAGAGGGACCGGTTCAACATTTTGAAGAAAGGGTCTCTGCACGGATATTTCTGAGACCCACAAAGGACGGTATGCTCAAGAATGTGAGGAACACCAGTACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTGCTGCGGACACAGTTCCCAGATGCATCATCACCTCAGGCTACTAGAAATCATCATTCTGACACCACAATCCTCCAGCACAGGGTTTTCCAACTATA";
private String contig2 = "ATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGAT";
private static final double DEFAULT_MISMATCH_RATE = .05;
@Test (groups = "unit" )
public void testMapExact() {
SimpleMapper sm = new SimpleMapper(contig1, DEFAULT_MISMATCH_RATE);
String read = "TACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTG";
SimpleMapperResult smr = sm.map(read);
assertEquals(0, smr.getMismatches());
assertEquals(257, smr.getPos()); | // Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
// Path: src/test/java/abra/SimpleMapperTest.java
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult;
package abra;
public class SimpleMapperTest {
private String contig1 = "TTCAACTAGAGAGAGGTAAAAATTTTTCTAGAACATGAATTGCCCACTCCCCTCATTCCTTCTCAGAAACTAACTGAATTCCAGTGGGTGTGCCTGGCAAACCCAAAAGCAGTTTCTGTTCAGGATGCTGGTCTTACCTGTGAAGGCGTTCATGAACGTGGAGAGGGACCGGTTCAACATTTTGAAGAAAGGGTCTCTGCACGGATATTTCTGAGACCCACAAAGGACGGTATGCTCAAGAATGTGAGGAACACCAGTACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTGCTGCGGACACAGTTCCCAGATGCATCATCACCTCAGGCTACTAGAAATCATCATTCTGACACCACAATCCTCCAGCACAGGGTTTTCCAACTATA";
private String contig2 = "ATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGATATCGATCGAT";
private static final double DEFAULT_MISMATCH_RATE = .05;
@Test (groups = "unit" )
public void testMapExact() {
SimpleMapper sm = new SimpleMapper(contig1, DEFAULT_MISMATCH_RATE);
String read = "TACTGTCCATGGGAGTGGTACGGAACTGCACGCTAGGGAAGAGAGAGGAATGGCACGCTAGGGAAGGCGAATGACCAGAACGCAAAAGGTTCAGCTTAGTG";
SimpleMapperResult smr = sm.map(read);
assertEquals(0, smr.getMismatches());
assertEquals(257, smr.getPos()); | assertEquals(Orientation.FORWARD, smr.getOrientation()); |
mozack/abra2 | src/main/java/htsjdk/samtools/util/SortingCollection2.java | // Path: src/main/java/abra/Logger.java
// public class Logger {
//
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
//
// public static Level LEVEL = Level.INFO;
//
// private static Map<String, Level> stringToLevel;
//
// static {
// stringToLevel = new HashMap<String, Level>();
// stringToLevel.put("TRACE", Level.TRACE);
// stringToLevel.put("DEBUG", Level.DEBUG);
// stringToLevel.put("INFO", Level.INFO);
// stringToLevel.put("WARN", Level.WARN);
// stringToLevel.put("ERROR", Level.ERROR);
// }
//
// // For trace or debug messages, use varargs to avoid string concatenation unless enabled
//
// public static void trace(String format, Object... args) {
// if (LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.TRACE);
// }
// }
//
// public static void debug(String format, Object... args) {
// if (LEVEL == Level.DEBUG || LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.DEBUG);
// }
// }
//
// public static void info(String format, Object... args) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO) {
// log(String.format(format, args), Level.INFO);
// }
// }
//
// public static void warn(String message) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO || LEVEL == Level.WARN) {
// log(message, Level.WARN);
// }
// }
//
// public static void error(String message) {
// log(message, Level.ERROR);
// }
//
// public static void setLevel(String str) {
// Level level = stringToLevel.get(str.toUpperCase());
// if (level == null) {
// throw new IllegalArgumentException("Log level must be one of trace, debug, info, warn or error.");
// }
//
// Logger.LEVEL = level;
// }
//
// public static void log(String message, Level level) {
//
// String levelStr = "UNKNOWN";
//
// switch (level) {
// case ERROR:
// levelStr = "ERROR";
// break;
// case WARN:
// levelStr = "WARNING";
// break;
// case INFO:
// levelStr = "INFO";
// break;
// case DEBUG:
// levelStr = "DEBUG";
// break;
// case TRACE:
// levelStr = "TRACE";
// break;
// }
//
// System.err.println(levelStr + "\t" + new Date() + "\t" + message);
// }
// }
| import htsjdk.samtools.Defaults;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import abra.Logger; |
if (this.numRecordsInRam > 0) {
spillToDisk();
}
// Facilitate GC
this.ramRecords = null;
}
/**
* @return True if this collection is allowed to discard data during iteration in order to reduce memory
* footprint, precluding a second iteration over the collection.
*/
public boolean isDestructiveIteration() {
return destructiveIteration;
}
/**
* Tell this collection that it is allowed to discard data during iteration in order to reduce memory footprint,
* precluding a second iteration. This is true by default.
*/
public void setDestructiveIteration(boolean destructiveIteration) {
this.destructiveIteration = destructiveIteration;
}
/**
* Sort the records in memory, write them to a file, and clear the buffer of records in memory.
*/
private void spillToDisk() {
try { | // Path: src/main/java/abra/Logger.java
// public class Logger {
//
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
//
// public static Level LEVEL = Level.INFO;
//
// private static Map<String, Level> stringToLevel;
//
// static {
// stringToLevel = new HashMap<String, Level>();
// stringToLevel.put("TRACE", Level.TRACE);
// stringToLevel.put("DEBUG", Level.DEBUG);
// stringToLevel.put("INFO", Level.INFO);
// stringToLevel.put("WARN", Level.WARN);
// stringToLevel.put("ERROR", Level.ERROR);
// }
//
// // For trace or debug messages, use varargs to avoid string concatenation unless enabled
//
// public static void trace(String format, Object... args) {
// if (LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.TRACE);
// }
// }
//
// public static void debug(String format, Object... args) {
// if (LEVEL == Level.DEBUG || LEVEL == Level.TRACE) {
// log(String.format(format, args), Level.DEBUG);
// }
// }
//
// public static void info(String format, Object... args) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO) {
// log(String.format(format, args), Level.INFO);
// }
// }
//
// public static void warn(String message) {
// if (LEVEL == Level.TRACE || LEVEL == Level.DEBUG || LEVEL == Level.INFO || LEVEL == Level.WARN) {
// log(message, Level.WARN);
// }
// }
//
// public static void error(String message) {
// log(message, Level.ERROR);
// }
//
// public static void setLevel(String str) {
// Level level = stringToLevel.get(str.toUpperCase());
// if (level == null) {
// throw new IllegalArgumentException("Log level must be one of trace, debug, info, warn or error.");
// }
//
// Logger.LEVEL = level;
// }
//
// public static void log(String message, Level level) {
//
// String levelStr = "UNKNOWN";
//
// switch (level) {
// case ERROR:
// levelStr = "ERROR";
// break;
// case WARN:
// levelStr = "WARNING";
// break;
// case INFO:
// levelStr = "INFO";
// break;
// case DEBUG:
// levelStr = "DEBUG";
// break;
// case TRACE:
// levelStr = "TRACE";
// break;
// }
//
// System.err.println(levelStr + "\t" + new Date() + "\t" + message);
// }
// }
// Path: src/main/java/htsjdk/samtools/util/SortingCollection2.java
import htsjdk.samtools.Defaults;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import abra.Logger;
if (this.numRecordsInRam > 0) {
spillToDisk();
}
// Facilitate GC
this.ramRecords = null;
}
/**
* @return True if this collection is allowed to discard data during iteration in order to reduce memory
* footprint, precluding a second iteration over the collection.
*/
public boolean isDestructiveIteration() {
return destructiveIteration;
}
/**
* Tell this collection that it is allowed to discard data during iteration in order to reduce memory footprint,
* precluding a second iteration. This is true by default.
*/
public void setDestructiveIteration(boolean destructiveIteration) {
this.destructiveIteration = destructiveIteration;
}
/**
* Sort the records in memory, write them to a file, and clear the buffer of records in memory.
*/
private void spillToDisk() {
try { | Logger.info("Sort Spilling to disk..."); |
mozack/abra2 | src/main/java/abra/ChromosomeChunker.java | // Path: src/main/java/abra/Logger.java
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import abra.Logger.Level; | currStart = nRegion.getStart()+1;
}
}
}
if (currStart < chromosomeLength) {
chunks.add(new Feature(chromosome, currStart, chromosomeLength));
}
*/
}
Logger.debug("Chromosome chunks:");
for (Feature chunk : chunks) {
Logger.debug(chunk.toString());
}
}
public List<Feature> getChunks() {
return chunks;
}
public Map<String, List<Integer>> getChunkGroups() {
return chunkGroups;
}
public List<String> getChromosomes() {
return c2r.getChromosomes();
}
public static void main(String[] args) throws Exception { | // Path: src/main/java/abra/Logger.java
// enum Level { TRACE, DEBUG, INFO, WARN, ERROR };
// Path: src/main/java/abra/ChromosomeChunker.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import abra.Logger.Level;
currStart = nRegion.getStart()+1;
}
}
}
if (currStart < chromosomeLength) {
chunks.add(new Feature(chromosome, currStart, chromosomeLength));
}
*/
}
Logger.debug("Chromosome chunks:");
for (Feature chunk : chunks) {
Logger.debug(chunk.toString());
}
}
public List<Feature> getChunks() {
return chunks;
}
public Map<String, List<Integer>> getChunkGroups() {
return chunkGroups;
}
public List<String> getChromosomes() {
return c2r.getChromosomes();
}
public static void main(String[] args) throws Exception { | Logger.LEVEL = Level.TRACE; |
mozack/abra2 | src/main/java/abra/ReadEvaluator.java | // Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
| import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult; | package abra;
public class ReadEvaluator {
// key = SimpleMapper with cached contig, value = contig SW alignment result
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> mappedContigs;
public ReadEvaluator(Map<Feature, Map<SimpleMapper, ContigAlignerResult>> mappedContigs) {
this.mappedContigs = mappedContigs;
}
/**
* If an improved alignment exists for the input read, return it.
* Returns null if there is no improved alignment
* If multiple alignments exist for the read with the same number of mismatches,
* the alignments are ambiguous and null is returned.
* A read may align to multiple contigs, but result in the same alignment in
* the context of the reference. In this case the alignment is considered distinct.
*/
public Alignment getImprovedAlignment(int origEditDist, SAMRecord samRecord, CompareToReference2 c2r) {
Alignment result = getImprovedAlignment(origEditDist, samRecord.getReadString());
if (result == null) {
// If soft clipped, attempt to map only the unclipped portion of the read
// Relying on the original mapper to handle clipping here
if (samRecord.getCigarString().contains("S")) {
// Use mapper's edit distance which should be for the unclipped portion of the read only
int unclippedEditDist = SAMRecordUtils.getEditDistance(samRecord, c2r, false);
// Don't bother remapping if alignment cannot be improved
if (unclippedEditDist > 0) {
String unclipped = SAMRecordUtils.getMappedReadPortion(samRecord);
result = getImprovedAlignment(unclippedEditDist, unclipped);
if (result != null) {
result.cigar = SAMRecordUtils.getLeadingClips(samRecord) + result.cigar + SAMRecordUtils.getTrailingClips(samRecord);
}
}
}
}
return result;
}
public Alignment getImprovedAlignment(int origEditDist, String read) {
Alignment result = null;
List<AlignmentHit> alignmentHits = new ArrayList<AlignmentHit>();
int bestMismatches = read.length()+1;
// Map read to all contigs, caching the hits with the smallest number of mismatches
for (Feature region : mappedContigs.keySet()) {
Map<SimpleMapper, ContigAlignerResult> regionContigs = mappedContigs.get(region);
for (SimpleMapper mapper : regionContigs.keySet()) { | // Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
// Path: src/main/java/abra/ReadEvaluator.java
import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult;
package abra;
public class ReadEvaluator {
// key = SimpleMapper with cached contig, value = contig SW alignment result
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> mappedContigs;
public ReadEvaluator(Map<Feature, Map<SimpleMapper, ContigAlignerResult>> mappedContigs) {
this.mappedContigs = mappedContigs;
}
/**
* If an improved alignment exists for the input read, return it.
* Returns null if there is no improved alignment
* If multiple alignments exist for the read with the same number of mismatches,
* the alignments are ambiguous and null is returned.
* A read may align to multiple contigs, but result in the same alignment in
* the context of the reference. In this case the alignment is considered distinct.
*/
public Alignment getImprovedAlignment(int origEditDist, SAMRecord samRecord, CompareToReference2 c2r) {
Alignment result = getImprovedAlignment(origEditDist, samRecord.getReadString());
if (result == null) {
// If soft clipped, attempt to map only the unclipped portion of the read
// Relying on the original mapper to handle clipping here
if (samRecord.getCigarString().contains("S")) {
// Use mapper's edit distance which should be for the unclipped portion of the read only
int unclippedEditDist = SAMRecordUtils.getEditDistance(samRecord, c2r, false);
// Don't bother remapping if alignment cannot be improved
if (unclippedEditDist > 0) {
String unclipped = SAMRecordUtils.getMappedReadPortion(samRecord);
result = getImprovedAlignment(unclippedEditDist, unclipped);
if (result != null) {
result.cigar = SAMRecordUtils.getLeadingClips(samRecord) + result.cigar + SAMRecordUtils.getTrailingClips(samRecord);
}
}
}
}
return result;
}
public Alignment getImprovedAlignment(int origEditDist, String read) {
Alignment result = null;
List<AlignmentHit> alignmentHits = new ArrayList<AlignmentHit>();
int bestMismatches = read.length()+1;
// Map read to all contigs, caching the hits with the smallest number of mismatches
for (Feature region : mappedContigs.keySet()) {
Map<SimpleMapper, ContigAlignerResult> regionContigs = mappedContigs.get(region);
for (SimpleMapper mapper : regionContigs.keySet()) { | SimpleMapperResult mapResult = mapper.map(read); |
mozack/abra2 | src/main/java/abra/ReadEvaluator.java | // Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
| import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult; | result = null;
}
} else if (alignments.size() > 1) {
// We have multiple possible alignments that are equal to the original alignment
if (bestMismatches == origEditDist) {
result = Alignment.AMBIGUOUS;
}
}
return result;
}
static class AlignmentHit {
SimpleMapperResult mapResult;
SimpleMapper mapper;
Feature region;
AlignmentHit(SimpleMapperResult mapResult, SimpleMapper mapper, Feature region) {
this.mapResult = mapResult;
this.mapper = mapper;
this.region = region;
}
}
//TODO: Genericize this and share ?
static class Alignment {
String chromosome;
int pos;
String cigar; | // Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// static class SimpleMapperResult {
// private int pos;
// private int mismatches;
// private Orientation orientation;
//
// SimpleMapperResult(int pos, int mismatches, Orientation orientation) {
// this.pos = pos;
// this.mismatches = mismatches;
// this.orientation = orientation;
// }
//
// public int getPos() {
// return pos;
// }
// public int getMismatches() {
// return mismatches;
// }
// public Orientation getOrientation() {
// return orientation;
// }
// }
// Path: src/main/java/abra/ReadEvaluator.java
import htsjdk.samtools.SAMRecord;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
import abra.SimpleMapper.SimpleMapperResult;
result = null;
}
} else if (alignments.size() > 1) {
// We have multiple possible alignments that are equal to the original alignment
if (bestMismatches == origEditDist) {
result = Alignment.AMBIGUOUS;
}
}
return result;
}
static class AlignmentHit {
SimpleMapperResult mapResult;
SimpleMapper mapper;
Feature region;
AlignmentHit(SimpleMapperResult mapResult, SimpleMapper mapper, Feature region) {
this.mapResult = mapResult;
this.mapper = mapper;
this.region = region;
}
}
//TODO: Genericize this and share ?
static class Alignment {
String chromosome;
int pos;
String cigar; | Orientation orientation; |
mozack/abra2 | src/test/java/abra/ReadEvaluatorTest.java | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
//
// Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
| import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation; | package abra;
public class ReadEvaluatorTest {
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> regionContigs;
private Map<SimpleMapper, ContigAlignerResult> mappedContigs;
@BeforeMethod ()
public void setUp() {
mappedContigs = new HashMap<SimpleMapper, ContigAlignerResult>();
regionContigs = new HashMap<Feature, Map<SimpleMapper, ContigAlignerResult>>();
regionContigs.put(new Feature("foo", 1, 1000), mappedContigs);
}
@Test (groups="unit")
public void testSingleAlignmentSingleContig() {
String contig1 = "ATCGAAAAAATTTTTTCCCCCCGGGGGGATCGGCTAATCG";
String read = "ATAAAATTTTTTCCCCCCGGGGGGATCG"; // matches contig at 0 based position 4 with 1 mismatch
SimpleMapper sm1 = new SimpleMapper(contig1, .05);
ContigAlignerResult swc1 = new ContigAlignerResult(10, "10M1D30M", "chr1", 0, contig1, (short) 1);
mappedContigs.put(sm1, swc1);
ReadEvaluator re = new ReadEvaluator(regionContigs);
// 1 mismatch in alignment to contig versus edit distance 2 in original read
// should result in an improved alignment | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
//
// Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
// Path: src/test/java/abra/ReadEvaluatorTest.java
import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
package abra;
public class ReadEvaluatorTest {
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> regionContigs;
private Map<SimpleMapper, ContigAlignerResult> mappedContigs;
@BeforeMethod ()
public void setUp() {
mappedContigs = new HashMap<SimpleMapper, ContigAlignerResult>();
regionContigs = new HashMap<Feature, Map<SimpleMapper, ContigAlignerResult>>();
regionContigs.put(new Feature("foo", 1, 1000), mappedContigs);
}
@Test (groups="unit")
public void testSingleAlignmentSingleContig() {
String contig1 = "ATCGAAAAAATTTTTTCCCCCCGGGGGGATCGGCTAATCG";
String read = "ATAAAATTTTTTCCCCCCGGGGGGATCG"; // matches contig at 0 based position 4 with 1 mismatch
SimpleMapper sm1 = new SimpleMapper(contig1, .05);
ContigAlignerResult swc1 = new ContigAlignerResult(10, "10M1D30M", "chr1", 0, contig1, (short) 1);
mappedContigs.put(sm1, swc1);
ReadEvaluator re = new ReadEvaluator(regionContigs);
// 1 mismatch in alignment to contig versus edit distance 2 in original read
// should result in an improved alignment | Alignment alignment = re.getImprovedAlignment(2, read); |
mozack/abra2 | src/test/java/abra/ReadEvaluatorTest.java | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
//
// Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
| import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation; | package abra;
public class ReadEvaluatorTest {
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> regionContigs;
private Map<SimpleMapper, ContigAlignerResult> mappedContigs;
@BeforeMethod ()
public void setUp() {
mappedContigs = new HashMap<SimpleMapper, ContigAlignerResult>();
regionContigs = new HashMap<Feature, Map<SimpleMapper, ContigAlignerResult>>();
regionContigs.put(new Feature("foo", 1, 1000), mappedContigs);
}
@Test (groups="unit")
public void testSingleAlignmentSingleContig() {
String contig1 = "ATCGAAAAAATTTTTTCCCCCCGGGGGGATCGGCTAATCG";
String read = "ATAAAATTTTTTCCCCCCGGGGGGATCG"; // matches contig at 0 based position 4 with 1 mismatch
SimpleMapper sm1 = new SimpleMapper(contig1, .05);
ContigAlignerResult swc1 = new ContigAlignerResult(10, "10M1D30M", "chr1", 0, contig1, (short) 1);
mappedContigs.put(sm1, swc1);
ReadEvaluator re = new ReadEvaluator(regionContigs);
// 1 mismatch in alignment to contig versus edit distance 2 in original read
// should result in an improved alignment
Alignment alignment = re.getImprovedAlignment(2, read);
assertEquals(alignment.pos, 14); // Alignment pos = 10 + 4
assertEquals(alignment.cigar, "6M1D22M");
assertEquals(alignment.numMismatches, 1); | // Path: src/main/java/abra/ReadEvaluator.java
// static class Alignment {
// String chromosome;
// int pos;
// String cigar;
// Orientation orientation;
// int numMismatches;
//
// int contigPos;
// String contigCigar;
// boolean isSecondary;
//
// static final Alignment AMBIGUOUS = new Alignment();
//
// Alignment() {
// }
//
// Alignment(String chromosome, int pos, String cigar, Orientation orientation, int numMismatches, int contigPos, String contigCigar, boolean isSecondary) {
// this.chromosome = chromosome;
// this.pos = pos;
// this.cigar = cigar;
// this.orientation = orientation;
// this.numMismatches = numMismatches;
//
// this.contigPos = contigPos;
// this.contigCigar = contigCigar;
// this.isSecondary = isSecondary;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((cigar == null) ? 0 : cigar.hashCode());
// result = prime * result
// + ((orientation == null) ? 0 : orientation.hashCode());
// result = prime * result + pos;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Alignment other = (Alignment) obj;
// if (cigar == null) {
// if (other.cigar != null)
// return false;
// } else if (!cigar.equals(other.cigar))
// return false;
// if (orientation != other.orientation)
// return false;
// if (pos != other.pos)
// return false;
// return true;
// }
//
// }
//
// Path: src/main/java/abra/ContigAligner.java
// public static class ContigAlignerResult {
//
// // Used for testing
// static boolean PAD_CONTIG = true;
//
// private int localRefPos;
// private String cigar;
//
// private String chromosome;
// private int refContextStart;
//
// private String sequence;
// private int score;
// private boolean isSecondary = false;
//
// public static final ContigAlignerResult INDEL_NEAR_END = new ContigAlignerResult();
//
// private ContigAlignerResult() {
// }
//
// ContigAlignerResult(int refPos, String cigar, String chromosome, int refContextStart, String sequence, int score) {
// this.localRefPos = refPos;
// this.cigar = cigar;
// this.chromosome = chromosome;
// this.refContextStart = refContextStart;
// this.sequence = sequence;
// this.score = score;
// }
//
// public int getRefPos() {
// return localRefPos;
// }
// public String getCigar() {
// return cigar;
// }
//
// public String getChromosome() {
// return chromosome;
// }
//
// public int getRefContextStart() {
// return refContextStart;
// }
//
// // This is the actual genomic position
// public int getGenomicPos() {
// return localRefPos + refContextStart;
// }
//
// public String getSequence() {
// return sequence;
// }
//
// public int getScore() {
// return score;
// }
//
// public boolean isSecondary() {
// return isSecondary;
// }
//
// public void setSecondary(boolean isSecondary) {
// this.isSecondary = isSecondary;
// }
// }
//
// Path: src/main/java/abra/SimpleMapper.java
// enum Orientation {
// UNSET, FORWARD, REVERSE;
// }
// Path: src/test/java/abra/ReadEvaluatorTest.java
import java.util.HashMap;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import abra.ReadEvaluator.Alignment;
import abra.ContigAligner.ContigAlignerResult;
import abra.SimpleMapper.Orientation;
package abra;
public class ReadEvaluatorTest {
private Map<Feature, Map<SimpleMapper, ContigAlignerResult>> regionContigs;
private Map<SimpleMapper, ContigAlignerResult> mappedContigs;
@BeforeMethod ()
public void setUp() {
mappedContigs = new HashMap<SimpleMapper, ContigAlignerResult>();
regionContigs = new HashMap<Feature, Map<SimpleMapper, ContigAlignerResult>>();
regionContigs.put(new Feature("foo", 1, 1000), mappedContigs);
}
@Test (groups="unit")
public void testSingleAlignmentSingleContig() {
String contig1 = "ATCGAAAAAATTTTTTCCCCCCGGGGGGATCGGCTAATCG";
String read = "ATAAAATTTTTTCCCCCCGGGGGGATCG"; // matches contig at 0 based position 4 with 1 mismatch
SimpleMapper sm1 = new SimpleMapper(contig1, .05);
ContigAlignerResult swc1 = new ContigAlignerResult(10, "10M1D30M", "chr1", 0, contig1, (short) 1);
mappedContigs.put(sm1, swc1);
ReadEvaluator re = new ReadEvaluator(regionContigs);
// 1 mismatch in alignment to contig versus edit distance 2 in original read
// should result in an improved alignment
Alignment alignment = re.getImprovedAlignment(2, read);
assertEquals(alignment.pos, 14); // Alignment pos = 10 + 4
assertEquals(alignment.cigar, "6M1D22M");
assertEquals(alignment.numMismatches, 1); | assertEquals(alignment.orientation, Orientation.FORWARD); |
mozack/abra2 | src/main/java/abra/Feature.java | // Path: src/main/java/abra/SAMRecordWrapper.java
// static class Span {
// int start;
// int end;
//
// public Span(int start, int end) {
// this.start = start;
// this.end = end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + end;
// result = prime * result + start;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Span other = (Span) obj;
// if (end != other.end)
// return false;
// if (start != other.start)
// return false;
// return true;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import abra.SAMRecordWrapper.Span;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord; |
public void setKmer(int kmer) {
this.kmerSize = kmer;
}
public static int findFirstOverlappingRegion(SAMFileHeader samHeader, SAMRecordWrapper read, int readStart, int readEnd, List<Feature> regions, int start) {
if (start < 0) {
start = 0;
}
for (int idx=start; idx<regions.size(); idx++) {
Feature region = regions.get(idx);
if ( (read.getSamRecord().getReferenceIndex() < samHeader.getSequenceDictionary().getSequenceIndex(region.getSeqname())) ||
(read.getSamRecord().getReferenceName().equals(region.getSeqname()) && readStart < region.getStart()) ) {
// This read is in between regions
// TODO: adjust start region here
return -1;
} else if (region.overlaps(read.getSamRecord().getReferenceName(), readStart, readEnd)) {
return idx;
}
}
// This read is beyond all regions
return -1;
}
public static List<Integer> findAllOverlappingRegions(SAMFileHeader samHeader, SAMRecordWrapper read, List<Feature> regions, int start) {
List<Integer> overlappingRegions = new ArrayList<Integer>();
| // Path: src/main/java/abra/SAMRecordWrapper.java
// static class Span {
// int start;
// int end;
//
// public Span(int start, int end) {
// this.start = start;
// this.end = end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + end;
// result = prime * result + start;
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Span other = (Span) obj;
// if (end != other.end)
// return false;
// if (start != other.start)
// return false;
// return true;
// }
// }
// Path: src/main/java/abra/Feature.java
import java.util.ArrayList;
import java.util.List;
import abra.SAMRecordWrapper.Span;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
public void setKmer(int kmer) {
this.kmerSize = kmer;
}
public static int findFirstOverlappingRegion(SAMFileHeader samHeader, SAMRecordWrapper read, int readStart, int readEnd, List<Feature> regions, int start) {
if (start < 0) {
start = 0;
}
for (int idx=start; idx<regions.size(); idx++) {
Feature region = regions.get(idx);
if ( (read.getSamRecord().getReferenceIndex() < samHeader.getSequenceDictionary().getSequenceIndex(region.getSeqname())) ||
(read.getSamRecord().getReferenceName().equals(region.getSeqname()) && readStart < region.getStart()) ) {
// This read is in between regions
// TODO: adjust start region here
return -1;
} else if (region.overlaps(read.getSamRecord().getReferenceName(), readStart, readEnd)) {
return idx;
}
}
// This read is beyond all regions
return -1;
}
public static List<Integer> findAllOverlappingRegions(SAMFileHeader samHeader, SAMRecordWrapper read, List<Feature> regions, int start) {
List<Integer> overlappingRegions = new ArrayList<Integer>();
| for (Span span : read.getSpanningRegions()) { |
GoogleContainerTools/minikube-build-tools-for-java | minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/MinikubeExtension.java | // Path: minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/util/CommandExecutorFactory.java
// public class CommandExecutorFactory {
// private final Logger logger;
//
// /**
// * Creates a new factory.
// *
// * @param logger for logging messages during the command execution
// */
// public CommandExecutorFactory(Logger logger) {
// this.logger = logger;
// }
//
// public CommandExecutor newCommandExecutor() {
// return new CommandExecutor().setLogger(logger);
// }
// }
//
// Path: minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/util/MinikubeDockerEnvParser.java
// public class MinikubeDockerEnvParser {
//
// private MinikubeDockerEnvParser() {}
//
// /**
// * Parses a list of KEY=VALUE strings into a map from KEY to VALUE.
// *
// * @param keyValueStrings a list of "KEY=VALUE" strings, where KEY is the environment variable
// * name and VALUE is the value to set it to
// */
// public static Map<String, String> parse(List<String> keyValueStrings) {
// Map<String, String> environmentMap = new HashMap<>();
//
// for (String keyValueString : keyValueStrings) {
// String[] keyValuePair = keyValueString.split("=", 2);
//
// if (keyValuePair.length < 2) {
// throw new IllegalArgumentException(
// "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format");
// }
// if (keyValuePair[0].length() == 0) {
// throw new IllegalArgumentException(
// "Error while parsing minikube's Docker environment: encountered empty environment variable name");
// }
//
// environmentMap.put(keyValuePair[0], keyValuePair[1]);
// }
//
// return environmentMap;
// }
// }
| import com.google.cloud.tools.minikube.util.CommandExecutorFactory;
import com.google.cloud.tools.minikube.util.MinikubeDockerEnvParser;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.gradle.api.Project;
import org.gradle.api.provider.Property; | /*
* Copyright 2017 Google 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.google.cloud.tools.minikube;
/** Minikube configuration extension. */
public class MinikubeExtension {
private final Property<String> minikube;
private final CommandExecutorFactory commandExecutorFactory;
public MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory) {
minikube = project.getObjects().property(String.class);
setMinikube("minikube");
this.commandExecutorFactory = commandExecutorFactory;
}
public String getMinikube() {
return minikube.get();
}
public void setMinikube(String minikube) {
this.minikube.set(minikube);
}
public Property<String> getMinikubeProvider() {
return minikube;
}
/**
* Gets the minikube docker environment variables by running the command 'minikube docker-env
* --shell=none'.
*
* @return A map of docker environment variables and their values
*/
public Map<String, String> getDockerEnv() throws IOException, InterruptedException {
return getDockerEnv("");
}
/**
* Gets the minikube docker environment variables by running the command 'minikube docker-env
* --shell=none'.
*
* @param profile target minikube profile
* @return A map of docker environment variables and their values
*/
public Map<String, String> getDockerEnv(String profile) throws IOException, InterruptedException {
if (profile == null) {
throw new NullPointerException("Minikube profile must not be null");
}
List<String> minikubeDockerEnvCommand =
Arrays.asList(minikube.get(), "docker-env", "--shell=none", "--profile=" + profile);
List<String> dockerEnv =
commandExecutorFactory.newCommandExecutor().run(minikubeDockerEnvCommand);
| // Path: minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/util/CommandExecutorFactory.java
// public class CommandExecutorFactory {
// private final Logger logger;
//
// /**
// * Creates a new factory.
// *
// * @param logger for logging messages during the command execution
// */
// public CommandExecutorFactory(Logger logger) {
// this.logger = logger;
// }
//
// public CommandExecutor newCommandExecutor() {
// return new CommandExecutor().setLogger(logger);
// }
// }
//
// Path: minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/util/MinikubeDockerEnvParser.java
// public class MinikubeDockerEnvParser {
//
// private MinikubeDockerEnvParser() {}
//
// /**
// * Parses a list of KEY=VALUE strings into a map from KEY to VALUE.
// *
// * @param keyValueStrings a list of "KEY=VALUE" strings, where KEY is the environment variable
// * name and VALUE is the value to set it to
// */
// public static Map<String, String> parse(List<String> keyValueStrings) {
// Map<String, String> environmentMap = new HashMap<>();
//
// for (String keyValueString : keyValueStrings) {
// String[] keyValuePair = keyValueString.split("=", 2);
//
// if (keyValuePair.length < 2) {
// throw new IllegalArgumentException(
// "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format");
// }
// if (keyValuePair[0].length() == 0) {
// throw new IllegalArgumentException(
// "Error while parsing minikube's Docker environment: encountered empty environment variable name");
// }
//
// environmentMap.put(keyValuePair[0], keyValuePair[1]);
// }
//
// return environmentMap;
// }
// }
// Path: minikube-gradle-plugin/src/main/java/com/google/cloud/tools/minikube/MinikubeExtension.java
import com.google.cloud.tools.minikube.util.CommandExecutorFactory;
import com.google.cloud.tools.minikube.util.MinikubeDockerEnvParser;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.gradle.api.Project;
import org.gradle.api.provider.Property;
/*
* Copyright 2017 Google 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.google.cloud.tools.minikube;
/** Minikube configuration extension. */
public class MinikubeExtension {
private final Property<String> minikube;
private final CommandExecutorFactory commandExecutorFactory;
public MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory) {
minikube = project.getObjects().property(String.class);
setMinikube("minikube");
this.commandExecutorFactory = commandExecutorFactory;
}
public String getMinikube() {
return minikube.get();
}
public void setMinikube(String minikube) {
this.minikube.set(minikube);
}
public Property<String> getMinikubeProvider() {
return minikube;
}
/**
* Gets the minikube docker environment variables by running the command 'minikube docker-env
* --shell=none'.
*
* @return A map of docker environment variables and their values
*/
public Map<String, String> getDockerEnv() throws IOException, InterruptedException {
return getDockerEnv("");
}
/**
* Gets the minikube docker environment variables by running the command 'minikube docker-env
* --shell=none'.
*
* @param profile target minikube profile
* @return A map of docker environment variables and their values
*/
public Map<String, String> getDockerEnv(String profile) throws IOException, InterruptedException {
if (profile == null) {
throw new NullPointerException("Minikube profile must not be null");
}
List<String> minikubeDockerEnvCommand =
Arrays.asList(minikube.get(), "docker-env", "--shell=none", "--profile=" + profile);
List<String> dockerEnv =
commandExecutorFactory.newCommandExecutor().run(minikubeDockerEnvCommand);
| return MinikubeDockerEnvParser.parse(dockerEnv); |
kbase/kb_sdk | src/java/us/kbase/templates/TemplateFormatter.java | // Path: src/java/us/kbase/mobu/util/TextUtils.java
// public class TextUtils {
// public static String capitalize(String text) {
// return capitalize(text, false);
// }
//
// public static String inCamelCase(String text) {
// return capitalize(text, true);
// }
//
// public static String capitalize(String text, boolean camel) {
// StringBuilder ret = new StringBuilder();
// StringTokenizer st = new StringTokenizer(text, "_-");
// boolean firstToken = true;
// while (st.hasMoreTokens()) {
// String token = st.nextToken();
// if (Character.isLowerCase(token.charAt(0)) && !(camel && firstToken)) {
// token = token.substring(0, 1).toUpperCase() + token.substring(1);
// }
// if (camel && firstToken && Character.isUpperCase(token.charAt(0))) {
// token = token.substring(0, 1).toLowerCase() + token.substring(1);
// }
// ret.append(token);
// firstToken = false;
// }
// return ret.toString();
// }
//
// public static List<String> readFileLines(File f) throws IOException {
// return readStreamLines(new FileInputStream(f));
// }
//
// public static String readFileText(File f) throws IOException {
// return readStreamText(new FileInputStream(f));
// }
//
// public static List<String> readStreamLines(InputStream is) throws IOException {
// return readStreamLines(is, true);
// }
//
// public static List<String> readStreamLines(InputStream is, boolean closeAfter) throws IOException {
// return readReaderLines(new InputStreamReader(is), closeAfter);
// }
//
// public static List<String> readReaderLines(Reader r, boolean closeAfter) throws IOException {
// BufferedReader br = new BufferedReader(r);
// List<String> ret = new ArrayList<String>();
// while (true) {
// String l = br.readLine();
// if (l == null)
// break;
// ret.add(l);
// }
// if (closeAfter)
// br.close();
// return ret;
// }
//
// public static void writeFileLines(List<String> lines, File targetFile) throws IOException {
// writeFileLines(lines, new FileWriter(targetFile));
// }
//
// public static void writeFileLines(List<String> lines, Writer targetFile) throws IOException {
// PrintWriter pw = new PrintWriter(targetFile);
// for (String l : lines)
// pw.print(l + "\n");
// pw.close();
// }
//
// public static void copyStreams(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[1024];
// int length;
// while ((length = is.read(buffer)) > 0) {
// os.write(buffer, 0, length);
// }
// is.close();
// os.close();
// }
//
// public static String readStreamText(InputStream is) throws IOException {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// copyStreams(is, baos);
// return new String(baos.toByteArray());
// }
//
// public static void deleteRecursively(File fileOrDir) {
// if (fileOrDir.isDirectory() && !Files.isSymbolicLink(fileOrDir.toPath())) {
// File[] files = fileOrDir.listFiles();
// if (files != null)
// for (File f : files)
// deleteRecursively(f);
// }
// fileOrDir.delete();
// }
//
// public static List<String> getLines(String text) throws Exception {
// BufferedReader br = new BufferedReader(new StringReader(text));
// List<String> ret = new ArrayList<String>();
// while (true) {
// String l = br.readLine();
// if (l == null)
// break;
// ret.add(l);
// }
// br.close();
// return ret;
// }
//
// public static void checkIgnoreLine(File f, String line) throws IOException {
// TextUtils.checkIgnoreLine(f, line, true);
// }
//
// public static void checkIgnoreLine(File f, String line, boolean showWarnings) throws IOException {
// List<String> lines = new ArrayList<String>();
// if (f.exists())
// lines.addAll(FileUtils.readLines(f));
// if (!new HashSet<String>(lines).contains(line)) {
// if(showWarnings) {
// System.out.println("Warning: file \"" + f.getName() + "\" doesn't contain \"" + line + "\" line, it will be added.");
// }
// lines.add(line);
// FileUtils.writeLines(f, lines);
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import us.kbase.mobu.util.TextUtils; | package us.kbase.templates;
public class TemplateFormatter {
public static boolean formatTemplate(String templateName, Map<?,?> context,
File output) throws IOException {
StringWriter sw = new StringWriter();
boolean ret = formatTemplate(templateName, context, sw);
sw.close();
StringReader sr = new StringReader(sw.toString()); | // Path: src/java/us/kbase/mobu/util/TextUtils.java
// public class TextUtils {
// public static String capitalize(String text) {
// return capitalize(text, false);
// }
//
// public static String inCamelCase(String text) {
// return capitalize(text, true);
// }
//
// public static String capitalize(String text, boolean camel) {
// StringBuilder ret = new StringBuilder();
// StringTokenizer st = new StringTokenizer(text, "_-");
// boolean firstToken = true;
// while (st.hasMoreTokens()) {
// String token = st.nextToken();
// if (Character.isLowerCase(token.charAt(0)) && !(camel && firstToken)) {
// token = token.substring(0, 1).toUpperCase() + token.substring(1);
// }
// if (camel && firstToken && Character.isUpperCase(token.charAt(0))) {
// token = token.substring(0, 1).toLowerCase() + token.substring(1);
// }
// ret.append(token);
// firstToken = false;
// }
// return ret.toString();
// }
//
// public static List<String> readFileLines(File f) throws IOException {
// return readStreamLines(new FileInputStream(f));
// }
//
// public static String readFileText(File f) throws IOException {
// return readStreamText(new FileInputStream(f));
// }
//
// public static List<String> readStreamLines(InputStream is) throws IOException {
// return readStreamLines(is, true);
// }
//
// public static List<String> readStreamLines(InputStream is, boolean closeAfter) throws IOException {
// return readReaderLines(new InputStreamReader(is), closeAfter);
// }
//
// public static List<String> readReaderLines(Reader r, boolean closeAfter) throws IOException {
// BufferedReader br = new BufferedReader(r);
// List<String> ret = new ArrayList<String>();
// while (true) {
// String l = br.readLine();
// if (l == null)
// break;
// ret.add(l);
// }
// if (closeAfter)
// br.close();
// return ret;
// }
//
// public static void writeFileLines(List<String> lines, File targetFile) throws IOException {
// writeFileLines(lines, new FileWriter(targetFile));
// }
//
// public static void writeFileLines(List<String> lines, Writer targetFile) throws IOException {
// PrintWriter pw = new PrintWriter(targetFile);
// for (String l : lines)
// pw.print(l + "\n");
// pw.close();
// }
//
// public static void copyStreams(InputStream is, OutputStream os) throws IOException {
// byte[] buffer = new byte[1024];
// int length;
// while ((length = is.read(buffer)) > 0) {
// os.write(buffer, 0, length);
// }
// is.close();
// os.close();
// }
//
// public static String readStreamText(InputStream is) throws IOException {
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// copyStreams(is, baos);
// return new String(baos.toByteArray());
// }
//
// public static void deleteRecursively(File fileOrDir) {
// if (fileOrDir.isDirectory() && !Files.isSymbolicLink(fileOrDir.toPath())) {
// File[] files = fileOrDir.listFiles();
// if (files != null)
// for (File f : files)
// deleteRecursively(f);
// }
// fileOrDir.delete();
// }
//
// public static List<String> getLines(String text) throws Exception {
// BufferedReader br = new BufferedReader(new StringReader(text));
// List<String> ret = new ArrayList<String>();
// while (true) {
// String l = br.readLine();
// if (l == null)
// break;
// ret.add(l);
// }
// br.close();
// return ret;
// }
//
// public static void checkIgnoreLine(File f, String line) throws IOException {
// TextUtils.checkIgnoreLine(f, line, true);
// }
//
// public static void checkIgnoreLine(File f, String line, boolean showWarnings) throws IOException {
// List<String> lines = new ArrayList<String>();
// if (f.exists())
// lines.addAll(FileUtils.readLines(f));
// if (!new HashSet<String>(lines).contains(line)) {
// if(showWarnings) {
// System.out.println("Warning: file \"" + f.getName() + "\" doesn't contain \"" + line + "\" line, it will be added.");
// }
// lines.add(line);
// FileUtils.writeLines(f, lines);
// }
// }
// }
// Path: src/java/us/kbase/templates/TemplateFormatter.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import us.kbase.mobu.util.TextUtils;
package us.kbase.templates;
public class TemplateFormatter {
public static boolean formatTemplate(String templateName, Map<?,?> context,
File output) throws IOException {
StringWriter sw = new StringWriter();
boolean ret = formatTemplate(templateName, context, sw);
sw.close();
StringReader sr = new StringReader(sw.toString()); | TextUtils.writeFileLines(TextUtils.readReaderLines(sr, true), output); |
kbase/kb_sdk | src/java/us/kbase/common/executionengine/CallbackServer.java | // Path: src/java/us/kbase/common/utils/NetUtils.java
// public class NetUtils {
// private static final Pattern IPADDRESS_PATTERN = Pattern.compile(
// "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
//
// public static List<String> findNetworkAddresses(String... networkNames)
// throws SocketException {
// Set<String> networkNameSet = new HashSet<String>(Arrays.asList(networkNames));
// List<String> ret = new ArrayList<String>();
// for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
// NetworkInterface intf = en.nextElement();
// // breaks linux, if required for windows needs to be os-dependent
// // if (!intf.isUp()) continue;
// if (networkNameSet.contains(intf.getName()) || networkNameSet.contains(intf.getDisplayName())) {
// for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
// String ip = enumIpAddr.nextElement().getHostAddress();
// if (IPADDRESS_PATTERN.matcher(ip).matches())
// ret.add(ip);
// }
// }
// }
// return ret;
// }
//
// public static int findFreePort() {
// try (ServerSocket socket = new ServerSocket(0)) {
// return socket.getLocalPort();
// } catch (IOException e) {}
// throw new IllegalStateException("Can not find available port in the system");
// }
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthToken;
import us.kbase.auth.ConfigurableAuthService;
import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig;
import us.kbase.common.service.JacksonTupleModule;
import us.kbase.common.service.JsonClientException;
import us.kbase.common.service.JsonServerMethod;
import us.kbase.common.service.JsonServerServlet;
import us.kbase.common.service.JsonServerSyslog;
import us.kbase.common.service.JsonTokenStream;
import us.kbase.common.service.RpcContext;
import us.kbase.common.service.UObject;
import us.kbase.common.utils.NetUtils;
import us.kbase.workspace.ProvenanceAction;
import us.kbase.workspace.SubAction; | }
protected abstract SubsequentCallRunner createJobRunner(
final AuthToken token,
final CallbackServerConfig config,
final UUID jobId,
final ModuleMethod modmeth,
final String serviceVer)
throws IOException, JsonClientException;
@Override
public void destroy() {
cbLog("Shutting down executor service");
final List<Runnable> failed = executor.shutdownNow();
if (!failed.isEmpty()) {
cbLog(String.format("Failed to stop %s tasks", failed.size()));
}
}
public static URL getCallbackUrl(int callbackPort)
throws SocketException {
return getCallbackUrl(callbackPort, null);
}
public static URL getCallbackUrl(int callbackPort, String[] networkInterfaces)
throws SocketException {
if (networkInterfaces == null || networkInterfaces.length == 0) {
networkInterfaces = new String[] {"docker0", "vboxnet0", "vboxnet1",
"VirtualBox Host-Only Ethernet Adapter", "en0"};
} | // Path: src/java/us/kbase/common/utils/NetUtils.java
// public class NetUtils {
// private static final Pattern IPADDRESS_PATTERN = Pattern.compile(
// "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
// "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
//
// public static List<String> findNetworkAddresses(String... networkNames)
// throws SocketException {
// Set<String> networkNameSet = new HashSet<String>(Arrays.asList(networkNames));
// List<String> ret = new ArrayList<String>();
// for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
// NetworkInterface intf = en.nextElement();
// // breaks linux, if required for windows needs to be os-dependent
// // if (!intf.isUp()) continue;
// if (networkNameSet.contains(intf.getName()) || networkNameSet.contains(intf.getDisplayName())) {
// for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
// String ip = enumIpAddr.nextElement().getHostAddress();
// if (IPADDRESS_PATTERN.matcher(ip).matches())
// ret.add(ip);
// }
// }
// }
// return ret;
// }
//
// public static int findFreePort() {
// try (ServerSocket socket = new ServerSocket(0)) {
// return socket.getLocalPort();
// } catch (IOException e) {}
// throw new IllegalStateException("Can not find available port in the system");
// }
// }
// Path: src/java/us/kbase/common/executionengine/CallbackServer.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthToken;
import us.kbase.auth.ConfigurableAuthService;
import us.kbase.common.executionengine.CallbackServerConfigBuilder.CallbackServerConfig;
import us.kbase.common.service.JacksonTupleModule;
import us.kbase.common.service.JsonClientException;
import us.kbase.common.service.JsonServerMethod;
import us.kbase.common.service.JsonServerServlet;
import us.kbase.common.service.JsonServerSyslog;
import us.kbase.common.service.JsonTokenStream;
import us.kbase.common.service.RpcContext;
import us.kbase.common.service.UObject;
import us.kbase.common.utils.NetUtils;
import us.kbase.workspace.ProvenanceAction;
import us.kbase.workspace.SubAction;
}
protected abstract SubsequentCallRunner createJobRunner(
final AuthToken token,
final CallbackServerConfig config,
final UUID jobId,
final ModuleMethod modmeth,
final String serviceVer)
throws IOException, JsonClientException;
@Override
public void destroy() {
cbLog("Shutting down executor service");
final List<Runnable> failed = executor.shutdownNow();
if (!failed.isEmpty()) {
cbLog(String.format("Failed to stop %s tasks", failed.size()));
}
}
public static URL getCallbackUrl(int callbackPort)
throws SocketException {
return getCallbackUrl(callbackPort, null);
}
public static URL getCallbackUrl(int callbackPort, String[] networkInterfaces)
throws SocketException {
if (networkInterfaces == null || networkInterfaces.length == 0) {
networkInterfaces = new String[] {"docker0", "vboxnet0", "vboxnet1",
"VirtualBox Host-Only Ethernet Adapter", "en0"};
} | final List<String> hostIps = NetUtils.findNetworkAddresses( |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/db/Video.java | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
| import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; | return false;
}
}
@Override
public int hashCode() {
return (getClass().hashCode() + getReadable_id().hashCode()) % Integer.MAX_VALUE;
}
/**
* Be sure to refresh this Video from the database before calling this, as it relies
* on a current value of download_staus.
*/
@Override
public int getDownloaded_video_count() {
return getDownload_status() == DL_STATUS_COMPLETE ? 1 : 0;
}
@Override
public int getVideo_count() {
return 1;
}
@Override
public String getId() {
return getReadable_id();
}
@Override | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
// Path: src/com/concentricsky/android/khanacademy/data/db/Video.java
import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
return false;
}
}
@Override
public int hashCode() {
return (getClass().hashCode() + getReadable_id().hashCode()) % Integer.MAX_VALUE;
}
/**
* Be sure to refresh this Video from the database before calling this, as it relies
* on a current value of download_staus.
*/
@Override
public int getDownloaded_video_count() {
return getDownload_status() == DL_STATUS_COMPLETE ? 1 : 0;
}
@Override
public int getVideo_count() {
return 1;
}
@Override
public String getId() {
return getReadable_id();
}
@Override | public BaseEntityUpdateVisitor<Video> buildUpdateVisitor() { |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/db/Video.java | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
| import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; | }
DownloadUrls urls = Video.this.getDownload_urls();
if (!isDefaultValue(urls, DownloadUrls.class)) {
toUpdate.setDownload_urls(urls);
}
int n = Video.this.getDuration();
if (!isDefaultValue(n, Integer.class)) {
toUpdate.setDuration(n);
}
n = Video.this.getViews();
if (!isDefaultValue(n, Integer.class)) {
toUpdate.setViews(n);
}
}
@Override
protected boolean isDefaultValue(Object value, Class<?> valueType) {
if (DownloadUrls.class.equals(valueType)) {
return null == value;
}
return super.isDefaultValue(value, valueType);
}
};
}
@Override | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
// Path: src/com/concentricsky/android/khanacademy/data/db/Video.java
import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
}
DownloadUrls urls = Video.this.getDownload_urls();
if (!isDefaultValue(urls, DownloadUrls.class)) {
toUpdate.setDownload_urls(urls);
}
int n = Video.this.getDuration();
if (!isDefaultValue(n, Integer.class)) {
toUpdate.setDuration(n);
}
n = Video.this.getViews();
if (!isDefaultValue(n, Integer.class)) {
toUpdate.setViews(n);
}
}
@Override
protected boolean isDefaultValue(Object value, Class<?> valueType) {
if (DownloadUrls.class.equals(valueType)) {
return null == value;
}
return super.isDefaultValue(value, valueType);
}
};
}
@Override | public void accept(EntityVisitor visitor) { |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/db/EntityBase.java | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
| import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.j256.ormlite.field.DatabaseField; | /*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data.db;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "kind",
visible = true,
defaultImpl = EntityBase.Impl.class
)
@JsonSubTypes({
@Type(value = Video.class, name = "Video"),
@Type(value = Topic.class, name = "Topic")
})
public abstract class EntityBase extends ModelBase {
public static class Impl extends EntityBase {
@Override public int getDownloaded_video_count() { return 0; }
@Override public int getVideo_count() { return 0; }
@Override
public String getId() {
throw new UnsupportedOperationException("But Videos and Topics have ids...");
}
@Override | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
// Path: src/com/concentricsky/android/khanacademy/data/db/EntityBase.java
import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.j256.ormlite.field.DatabaseField;
/*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data.db;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "kind",
visible = true,
defaultImpl = EntityBase.Impl.class
)
@JsonSubTypes({
@Type(value = Video.class, name = "Video"),
@Type(value = Topic.class, name = "Topic")
})
public abstract class EntityBase extends ModelBase {
public static class Impl extends EntityBase {
@Override public int getDownloaded_video_count() { return 0; }
@Override public int getVideo_count() { return 0; }
@Override
public String getId() {
throw new UnsupportedOperationException("But Videos and Topics have ids...");
}
@Override | public BaseEntityUpdateVisitor<Impl> buildUpdateVisitor() { |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/db/EntityBase.java | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
| import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.j256.ormlite.field.DatabaseField; | /*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data.db;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "kind",
visible = true,
defaultImpl = EntityBase.Impl.class
)
@JsonSubTypes({
@Type(value = Video.class, name = "Video"),
@Type(value = Topic.class, name = "Topic")
})
public abstract class EntityBase extends ModelBase {
public static class Impl extends EntityBase {
@Override public int getDownloaded_video_count() { return 0; }
@Override public int getVideo_count() { return 0; }
@Override
public String getId() {
throw new UnsupportedOperationException("But Videos and Topics have ids...");
}
@Override
public BaseEntityUpdateVisitor<Impl> buildUpdateVisitor() {
return new BaseEntityUpdateVisitor<Impl>(this) { };
}
@Override | // Path: src/com/concentricsky/android/khanacademy/data/remote/BaseEntityUpdateVisitor.java
// public abstract class BaseEntityUpdateVisitor<T extends EntityBase> implements EntityVisitor {
// private T updateFrom;
// public BaseEntityUpdateVisitor(T updateFrom) {
// this.updateFrom = updateFrom;
// }
// @Override
// public void visit(Topic topic) {
// baseUpdate(topic);
// }
// @Override
// public void visit(Video video) {
// baseUpdate(video);
// }
// @Override
// public void visit(EntityBase.Impl entity) {
// baseUpdate(entity);
// }
// private void baseUpdate(EntityBase toUpdate) {
// String value = updateFrom.getTitle();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setTitle(value);
// }
//
// value = updateFrom.getDescription();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setDescription(value);
// }
//
// value = updateFrom.getHide();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setHide(value);
// }
//
// value = updateFrom.getKa_url();
// if (!isDefaultValue(value, String.class)) {
// toUpdate.setKa_url(value);
// }
//
// Topic parent = updateFrom.getParentTopic();
// if (!isDefaultValue(parent, Topic.class)) {
// toUpdate.setParentTopic(parent);
// }
//
// }
//
// /**
// * Test a value to see if it is the default value for its type.
// *
// * @param value The value to check.
// * @param valueType The value's class. In case of primitives, pass the wrapper class, such as Integer.
// * @return true if the value is default for fields of the given type on this class, false otherwise.
// */
// protected boolean isDefaultValue(Object value, Class<?> valueType) {
//
// if (String.class.equals(valueType)) {
// return null == value || "".equals(value);
// } else if (Integer.class.equals(valueType)) {
// return Integer.valueOf(0).equals(value);
// } else if (Topic.class.equals(valueType)) {
// return null == value;
// }
//
// throw new UnsupportedOperationException(String.format("Unknown type: %s", valueType.getSimpleName()));
// }
//
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/remote/EntityVisitor.java
// public interface EntityVisitor {
// public void visit(Topic topic);
// public void visit(Video video);
// public void visit(EntityBase.Impl entity);
// }
// Path: src/com/concentricsky/android/khanacademy/data/db/EntityBase.java
import com.concentricsky.android.khanacademy.data.remote.BaseEntityUpdateVisitor;
import com.concentricsky.android.khanacademy.data.remote.EntityVisitor;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.j256.ormlite.field.DatabaseField;
/*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data.db;
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "kind",
visible = true,
defaultImpl = EntityBase.Impl.class
)
@JsonSubTypes({
@Type(value = Video.class, name = "Video"),
@Type(value = Topic.class, name = "Topic")
})
public abstract class EntityBase extends ModelBase {
public static class Impl extends EntityBase {
@Override public int getDownloaded_video_count() { return 0; }
@Override public int getVideo_count() { return 0; }
@Override
public String getId() {
throw new UnsupportedOperationException("But Videos and Topics have ids...");
}
@Override
public BaseEntityUpdateVisitor<Impl> buildUpdateVisitor() {
return new BaseEntityUpdateVisitor<Impl>(this) { };
}
@Override | public void accept(EntityVisitor visitor) { |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
| import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException; | /*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data;
public class KADataServiceProviderImpl implements Provider {
private Activity activity;
private KADataService dataService; | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
// Path: src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java
import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException;
/*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data;
public class KADataServiceProviderImpl implements Provider {
private Activity activity;
private KADataService dataService; | private List<ObjectCallback<KADataService>> dataServiceCallbacks = new ArrayList<ObjectCallback<KADataService>>(); |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
| import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException; | /*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data;
public class KADataServiceProviderImpl implements Provider {
private Activity activity;
private KADataService dataService;
private List<ObjectCallback<KADataService>> dataServiceCallbacks = new ArrayList<ObjectCallback<KADataService>>();
private boolean dataServiceExpected;
private boolean serviceRequested;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// NOTE : we ignore the name, as we only connect to a single type of dataService. | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
// Path: src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java
import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException;
/*
Viewer for Khan Academy
Copyright (C) 2012 Concentric Sky, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.concentricsky.android.khanacademy.data;
public class KADataServiceProviderImpl implements Provider {
private Activity activity;
private KADataService dataService;
private List<ObjectCallback<KADataService>> dataServiceCallbacks = new ArrayList<ObjectCallback<KADataService>>();
private boolean dataServiceExpected;
private boolean serviceRequested;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// NOTE : we ignore the name, as we only connect to a single type of dataService. | dataService = ((KADataBinder) service).getService(); |
concentricsky/android-viewer-for-khan-academy | src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
| import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException; | callback.call(dataService);
}
dataServiceCallbacks.clear();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// NOTE : we ignore the name, as we only connect to a single type of dataService.
dataService = null;
}
};
public void destroy() {
dataServiceCallbacks.clear();
if (serviceRequested) {
activity.unbindService(serviceConnection);
}
activity = null;
serviceConnection = null;
dataService = null;
}
public KADataServiceProviderImpl(Activity activity) {
this.activity = activity;
serviceRequested = false;
}
@Override | // Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class KADataBinder extends Binder {
// private KADataService dataService;
// public KADataBinder(KADataService dataService) {
// setDataService(dataService);
// }
// public KADataService getService() {
// return dataService;
// }
// public void setDataService(KADataService dataService) {
// this.dataService = dataService;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public interface Provider {
// public KADataService getDataService() throws ServiceUnavailableException;
// public boolean requestDataService(ObjectCallback<KADataService> callback);
// public boolean cancelDataServiceRequest(ObjectCallback<KADataService> callback);
// }
//
// Path: src/com/concentricsky/android/khanacademy/data/KADataService.java
// public static class ServiceUnavailableException extends Exception {
// private static final long serialVersionUID = 581386365380491650L;
// public final boolean expected;
// public ServiceUnavailableException(boolean expected) {
// super();
// this.expected = expected;
// }
// }
//
// Path: src/com/concentricsky/android/khanacademy/util/ObjectCallback.java
// public interface ObjectCallback<T> {
// public void call(T obj);
// }
// Path: src/com/concentricsky/android/khanacademy/data/KADataServiceProviderImpl.java
import com.concentricsky.android.khanacademy.util.ObjectCallback;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.concentricsky.android.khanacademy.data.KADataService.KADataBinder;
import com.concentricsky.android.khanacademy.data.KADataService.Provider;
import com.concentricsky.android.khanacademy.data.KADataService.ServiceUnavailableException;
callback.call(dataService);
}
dataServiceCallbacks.clear();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// NOTE : we ignore the name, as we only connect to a single type of dataService.
dataService = null;
}
};
public void destroy() {
dataServiceCallbacks.clear();
if (serviceRequested) {
activity.unbindService(serviceConnection);
}
activity = null;
serviceConnection = null;
dataService = null;
}
public KADataServiceProviderImpl(Activity activity) {
this.activity = activity;
serviceRequested = false;
}
@Override | public KADataService getDataService() throws ServiceUnavailableException { |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
| // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
| private final XRequestResolver requestResolver; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final InetSocketAddress udpSource; | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final InetSocketAddress udpSource; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final InetSocketAddress udpSource;
private final Wrapper wrapper;
public Tcp2UdpHandler(InetSocketAddress udpSource, XRequestResolver requestResolver, Wrapper wrapper) {
this.udpSource = udpSource;
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel udpChannel = XChannelMapper.getUdpChannel(udpSource);
if (udpChannel == null) {
log.warn("Bad Connection! (udp channel closed)");
XChannelMapper.closeChannelGracefullyByTcpChannel(ctx.channel());
} else if (udpChannel.isActive()) {
ByteBuf byteBuf = (ByteBuf) msg;
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
bytes = wrapper.unwrap(bytes); | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final InetSocketAddress udpSource;
private final Wrapper wrapper;
public Tcp2UdpHandler(InetSocketAddress udpSource, XRequestResolver requestResolver, Wrapper wrapper) {
this.udpSource = udpSource;
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Channel udpChannel = XChannelMapper.getUdpChannel(udpSource);
if (udpChannel == null) {
log.warn("Bad Connection! (udp channel closed)");
XChannelMapper.closeChannelGracefullyByTcpChannel(ctx.channel());
} else if (udpChannel.isActive()) {
ByteBuf byteBuf = (ByteBuf) msg;
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
bytes = wrapper.unwrap(bytes); | XRequest request = requestResolver.parse(bytes); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/wrapper/ZeroPaddingWrapper.java | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.util.KeyHelper;
import java.util.Arrays; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class ZeroPaddingWrapper extends PaddingWrapper {
// +-----------------------+--------------------+------+
// | header (padding size) | padding (nullable) | data |
// +-----------------------+--------------------+------+
public ZeroPaddingWrapper(int paddingThreshold, int paddingRange) {
super(paddingThreshold, paddingRange);
if (paddingThreshold + paddingRange < 0xFF - 1)
headerLength = 1;
else if (paddingThreshold + paddingRange < 0xFFFF - 2)
headerLength = 2;
else if (paddingThreshold + paddingRange < 0xFFFFFF - 3)
headerLength = 3;
}
@Override
public byte[] wrap(byte[] bytes) {
if (bytes.length < paddingThreshold + paddingRange) { | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/wrapper/ZeroPaddingWrapper.java
import cc.agentx.util.KeyHelper;
import java.util.Arrays;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class ZeroPaddingWrapper extends PaddingWrapper {
// +-----------------------+--------------------+------+
// | header (padding size) | padding (nullable) | data |
// +-----------------------+--------------------+------+
public ZeroPaddingWrapper(int paddingThreshold, int paddingRange) {
super(paddingThreshold, paddingRange);
if (paddingThreshold + paddingRange < 0xFF - 1)
headerLength = 1;
else if (paddingThreshold + paddingRange < 0xFFFF - 2)
headerLength = 2;
else if (paddingThreshold + paddingRange < 0xFFFFFF - 3)
headerLength = 3;
}
@Override
public byte[] wrap(byte[] bytes) {
if (bytes.length < paddingThreshold + paddingRange) { | int randomLength = KeyHelper.generateRandomInteger( |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/wrapper/FrameWrapper.java | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.util.KeyHelper;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | reservedHeaderLength = 4;
}
/**
* frameHandler will be invoked before the frame re-concat into
* data stream, see unwrap().
*/
public FrameWrapper(int fixedFrameLength, Wrapper frameHandler) {
this(fixedFrameLength);
this.frameHandler = frameHandler;
}
/*
* data will be wrapped into several frames, but marked as a whole
* chunk (we call it a data-package)
*/
@Override
public byte[] wrap(final byte[] bytes) {
byte[] payload;
if (frameHandler == null) {
payload = bytes;
} else {
payload = frameHandler.wrap(bytes);
}
int i, nof = (payload.length / frameLength) + (payload.length % frameLength == 0 ? 0 : 1);
for (i = 0; i < nof - 1; i++) {
wrapBuffer.write(1);
wrapBuffer.write(payload, i * frameLength, frameLength);
}
wrapBuffer.write(0); | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/wrapper/FrameWrapper.java
import cc.agentx.util.KeyHelper;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
reservedHeaderLength = 4;
}
/**
* frameHandler will be invoked before the frame re-concat into
* data stream, see unwrap().
*/
public FrameWrapper(int fixedFrameLength, Wrapper frameHandler) {
this(fixedFrameLength);
this.frameHandler = frameHandler;
}
/*
* data will be wrapped into several frames, but marked as a whole
* chunk (we call it a data-package)
*/
@Override
public byte[] wrap(final byte[] bytes) {
byte[] payload;
if (frameHandler == null) {
payload = bytes;
} else {
payload = frameHandler.wrap(bytes);
}
int i, nof = (payload.length / frameLength) + (payload.length % frameLength == 0 ? 0 : 1);
for (i = 0; i < nof - 1; i++) {
wrapBuffer.write(1);
wrapBuffer.write(payload, i * frameLength, frameLength);
}
wrapBuffer.write(0); | wrapBuffer.write(KeyHelper.getBytes(reservedHeaderLength, payload.length - i * frameLength), 0, reservedHeaderLength); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/ui/HttpError.java | // Path: src/main/java/cc/agentx/Constants.java
// public final class Constants {
// public static final String APP_NAME = "agentx";
// public static final String APP_VERSION = "1.3";
// public static final String WEB_SERVER_NAME = "agentx-web-console";
//
// private Constants() {
// }
// }
| import cc.agentx.Constants;
import java.util.regex.Matcher; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.ui;
/**
* <b>Notice:</b> this project is not for a web server,
* you can see that the page configuration is embedded into
* <code>cc.agentx.http.Initializer</code>. <br>However,
* <code>cc.agentx.http</code> is designed separately,
* it can be extracted into a single project.
* <br>
* Thus, this web server project might be developed in the future,
* hold on and keep attention :)
*/
public class HttpError extends Throwable {
public static final HttpError HTTP_400 = new HttpError(400, "Bad Request");
public static final HttpError HTTP_404 = new HttpError(404, "Not Found");
public static final HttpError HTTP_405 = new HttpError(405, "Method Not Allowed");
public static final HttpError HTTP_408 = new HttpError(405, "Request Timeout");
public static final HttpError HTTP_500 = new HttpError(500, "Internal Server Error");
private static final String ERROR_PAGE_CONTENT = Initializer.getStaticErrorPage();
private final int code;
private final String text;
HttpError(final int code, final String text) {
this.code = code;
this.text = text;
}
public static String wrapInErrorPage(String bodyText) {
return ERROR_PAGE_CONTENT.replaceAll(Matcher.quoteReplacement("$0"), bodyText)
.replaceAll(Matcher.quoteReplacement("$1"), bodyText) | // Path: src/main/java/cc/agentx/Constants.java
// public final class Constants {
// public static final String APP_NAME = "agentx";
// public static final String APP_VERSION = "1.3";
// public static final String WEB_SERVER_NAME = "agentx-web-console";
//
// private Constants() {
// }
// }
// Path: src/main/java/cc/agentx/ui/HttpError.java
import cc.agentx.Constants;
import java.util.regex.Matcher;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.ui;
/**
* <b>Notice:</b> this project is not for a web server,
* you can see that the page configuration is embedded into
* <code>cc.agentx.http.Initializer</code>. <br>However,
* <code>cc.agentx.http</code> is designed separately,
* it can be extracted into a single project.
* <br>
* Thus, this web server project might be developed in the future,
* hold on and keep attention :)
*/
public class HttpError extends Throwable {
public static final HttpError HTTP_400 = new HttpError(400, "Bad Request");
public static final HttpError HTTP_404 = new HttpError(404, "Not Found");
public static final HttpError HTTP_405 = new HttpError(405, "Method Not Allowed");
public static final HttpError HTTP_408 = new HttpError(405, "Request Timeout");
public static final HttpError HTTP_500 = new HttpError(500, "Internal Server Error");
private static final String ERROR_PAGE_CONTENT = Initializer.getStaticErrorPage();
private final int code;
private final String text;
HttpError(final int code, final String text) {
this.code = code;
this.text = text;
}
public static String wrapInErrorPage(String bodyText) {
return ERROR_PAGE_CONTENT.replaceAll(Matcher.quoteReplacement("$0"), bodyText)
.replaceAll(Matcher.quoteReplacement("$1"), bodyText) | .replaceAll(Matcher.quoteReplacement("$2"), "AgentX " + Constants.APP_VERSION) |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/security/AesCipher.java | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.util.KeyHelper;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import javax.crypto.spec.SecretKeySpec; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.security;
public class AesCipher extends Cipher {
// encryption mode
public static final int AES_128_CFB = 16;
public static final int AES_192_CFB = 24;
public static final int AES_256_CFB = 32;
public static final int AES_128_OFB = -16;
public static final int AES_192_OFB = -24;
public static final int AES_256_OFB = -32;
private final int keyLength;
private final StreamBlockCipher cipher;
/**
* <b>Notice: </b><br>
* 1. the <code>AESFastEngine</code> was replaced by <code>AESEngine</code> now.<br>
* 2. in <code>new CFBBlockCipher(engine, <b>16</b> * 8);</code> the IV length (16) is
* reference to the shadowsocks's design.
*
* @see <a href="https://www.bouncycastle.org/releasenotes.html">
* https://www.bouncycastle.org/releasenotes.html</a>#CVE-2016-1000339<br>
* <a href="https://shadowsocks.org/en/spec/cipher.html">
* https://shadowsocks.org/en/spec/cipher.html</a>#Cipher
*/
public AesCipher(String password, int mode) {
key = new SecretKeySpec(password.getBytes(), "AES");
keyLength = Math.abs(mode);
AESEngine engine = new AESEngine();
if (mode > 0) {
cipher = new CFBBlockCipher(engine, 16 * 8);
} else {
cipher = new OFBBlockCipher(engine, 16 * 8);
}
}
public static boolean isValidMode(int mode) {
int modeAbs = Math.abs(mode);
return modeAbs == 16 || modeAbs == 24 || modeAbs == 32;
}
@Override
protected void _init(boolean isEncrypt, byte[] iv) {
String keyStr = new String(key.getEncoded());
ParametersWithIV params = new ParametersWithIV( | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/security/AesCipher.java
import cc.agentx.util.KeyHelper;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import javax.crypto.spec.SecretKeySpec;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.security;
public class AesCipher extends Cipher {
// encryption mode
public static final int AES_128_CFB = 16;
public static final int AES_192_CFB = 24;
public static final int AES_256_CFB = 32;
public static final int AES_128_OFB = -16;
public static final int AES_192_OFB = -24;
public static final int AES_256_OFB = -32;
private final int keyLength;
private final StreamBlockCipher cipher;
/**
* <b>Notice: </b><br>
* 1. the <code>AESFastEngine</code> was replaced by <code>AESEngine</code> now.<br>
* 2. in <code>new CFBBlockCipher(engine, <b>16</b> * 8);</code> the IV length (16) is
* reference to the shadowsocks's design.
*
* @see <a href="https://www.bouncycastle.org/releasenotes.html">
* https://www.bouncycastle.org/releasenotes.html</a>#CVE-2016-1000339<br>
* <a href="https://shadowsocks.org/en/spec/cipher.html">
* https://shadowsocks.org/en/spec/cipher.html</a>#Cipher
*/
public AesCipher(String password, int mode) {
key = new SecretKeySpec(password.getBytes(), "AES");
keyLength = Math.abs(mode);
AESEngine engine = new AESEngine();
if (mode > 0) {
cipher = new CFBBlockCipher(engine, 16 * 8);
} else {
cipher = new OFBBlockCipher(engine, 16 * 8);
}
}
public static boolean isValidMode(int mode) {
int modeAbs = Math.abs(mode);
return modeAbs == 16 || modeAbs == 24 || modeAbs == 32;
}
@Override
protected void _init(boolean isEncrypt, byte[] iv) {
String keyStr = new String(key.getEncoded());
ParametersWithIV params = new ParametersWithIV( | new KeyParameter(KeyHelper.generateKeyDigest(keyLength, keyStr)), iv |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
| // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
| private final XRequestResolver requestResolver; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver; | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
public Udp2TcpHandler(XRequestResolver requestResolver, Wrapper wrapper) {
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
DatagramPacket datagram = (DatagramPacket) msg;
InetSocketAddress sender = datagram.sender();
Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
if (tcpChannel == null) {
// udpSource not registered, actively discard this packet
// without register, an udp channel cannot relate to any tcp channel, so remove the map
XChannelMapper.removeUdpMapping(sender);
log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
} else if (tcpChannel.isActive()) {
ByteBuf byteBuf = datagram.content();
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
log.info("\t Proxy << Target \tFrom {}:{}", sender.getHostString(), sender.getPort());
// write udp payload via tcp channel | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
public Udp2TcpHandler(XRequestResolver requestResolver, Wrapper wrapper) {
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
DatagramPacket datagram = (DatagramPacket) msg;
InetSocketAddress sender = datagram.sender();
Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
if (tcpChannel == null) {
// udpSource not registered, actively discard this packet
// without register, an udp channel cannot relate to any tcp channel, so remove the map
XChannelMapper.removeUdpMapping(sender);
log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
} else if (tcpChannel.isActive()) {
ByteBuf byteBuf = datagram.content();
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
log.info("\t Proxy << Target \tFrom {}:{}", sender.getHostString(), sender.getPort());
// write udp payload via tcp channel | tcpChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes)))); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
| // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
| private final XRequestResolver requestResolver; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver; | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
public Udp2TcpHandler(XRequestResolver requestResolver, Wrapper wrapper) {
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
DatagramPacket datagram = (DatagramPacket) msg;
InetSocketAddress sender = datagram.sender();
Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
if (tcpChannel == null) {
// udpSource not registered, actively discard this packet
// without register, an udp channel cannot relate to any tcp channel, so remove the map
XChannelMapper.removeUdpMapping(sender);
log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
} else if (tcpChannel.isActive()) {
ByteBuf byteBuf = datagram.content();
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
// write udp payload via tcp channel | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/Udp2TcpHandler.java
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public class Udp2TcpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(Udp2TcpHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
public Udp2TcpHandler(XRequestResolver requestResolver, Wrapper wrapper) {
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
DatagramPacket datagram = (DatagramPacket) msg;
InetSocketAddress sender = datagram.sender();
Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
if (tcpChannel == null) {
// udpSource not registered, actively discard this packet
// without register, an udp channel cannot relate to any tcp channel, so remove the map
XChannelMapper.removeUdpMapping(sender);
log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
} else if (tcpChannel.isActive()) {
ByteBuf byteBuf = datagram.content();
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
// write udp payload via tcp channel | byte[] content = wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes)); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
| // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
| private final XRequestResolver requestResolver; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver; | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
private InetSocketAddress udpTarget;
public Tcp2UdpHandler(InetSocketAddress udpTarget, XRequestResolver requestResolver, Wrapper wrapper) {
this.udpTarget = udpTarget;
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf byteBuf = (ByteBuf) msg;
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
bytes = wrapper.unwrap(bytes);
// resolve xRequest | // Path: src/main/java/cc/agentx/protocol/request/XRequest.java
// public class XRequest {
// private Type atyp;
// private String host;
// private int port;
// private int subsequentDataLength;
// private Channel channel = Channel.TCP;
//
// public XRequest(Type atyp, String host, int port, int subsequentDataLength) {
// this.atyp = atyp;
// this.host = host;
// this.port = port;
// this.subsequentDataLength = subsequentDataLength;
// }
//
// public XRequest(byte[] bytes) {
// String[] target = new String(bytes).split(":");
// if (target[0].equals(Type.IPV4.name()))
// this.atyp = Type.IPV4;
// if (target[0].equals(Type.DOMAIN.name()))
// this.atyp = Type.DOMAIN;
// if (target[0].equals(Type.IPV6.name()))
// this.atyp = Type.IPV6;
// this.host = target[1];
// this.port = Integer.parseInt(target[2]);
// this.subsequentDataLength = Integer.parseInt(target[3]);
// }
//
// public Channel getChannel() {
// return channel;
// }
//
// public XRequest setChannel(Channel channel) {
// this.channel = channel;
// return this;
// }
//
// public byte[] getBytes() {
// return (atyp.name() + ":" + host + ":" + port + ":" + subsequentDataLength).getBytes();
// }
//
// public String getHost() {
// return host;
// }
//
// public int getPort() {
// return port;
// }
//
// public int getSubsequentDataLength() {
// return subsequentDataLength;
// }
//
// public Type getAtyp() {
// return atyp;
// }
//
// @Override
// public String toString() {
// return "XRequest{" +
// "atyp=" + atyp +
// ", host='" + host + '\'' +
// ", port=" + port +
// ", subsequentDataLength=" + subsequentDataLength +
// ", channel=" + channel +
// '}';
// }
//
// public enum Channel {
// TCP, UDP
// }
//
// public enum Type {
// IPV4, DOMAIN, IPV6, UNKNOWN
// }
// }
//
// Path: src/main/java/cc/agentx/protocol/request/XRequestResolver.java
// public abstract class XRequestResolver {
//
// public abstract byte[] wrap(XRequest.Channel channel, byte[] bytes);
//
// public abstract XRequest parse(final byte[] bytes);
//
// public abstract boolean exposeRequest();
//
// public byte[] wrap(byte[] bytes) {
// return wrap(XRequest.Channel.TCP, bytes);
// }
//
// public byte[] unwrap(final byte[] bytes) {
// return parse(bytes).getBytes();
// }
// }
//
// Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/Tcp2UdpHandler.java
import java.net.InetSocketAddress;
import java.util.Arrays;
import cc.agentx.protocol.request.XRequest;
import cc.agentx.protocol.request.XRequestResolver;
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class Tcp2UdpHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final XRequestResolver requestResolver;
private final Wrapper wrapper;
private InetSocketAddress udpTarget;
public Tcp2UdpHandler(InetSocketAddress udpTarget, XRequestResolver requestResolver, Wrapper wrapper) {
this.udpTarget = udpTarget;
this.requestResolver = requestResolver;
this.wrapper = wrapper;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf byteBuf = (ByteBuf) msg;
try {
if (!byteBuf.hasArray()) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.getBytes(0, bytes);
bytes = wrapper.unwrap(bytes);
// resolve xRequest | XRequest request = requestResolver.parse(bytes); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/ui/HttpServer.java | // Path: src/main/java/cc/agentx/Constants.java
// public final class Constants {
// public static final String APP_NAME = "agentx";
// public static final String APP_VERSION = "1.3";
// public static final String WEB_SERVER_NAME = "agentx-web-console";
//
// private Constants() {
// }
// }
| import cc.agentx.Constants;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; | port = getIdlePort();
baseDir = System.getProperty("user.dir").replaceAll("\\\\", "/") + "/www/";
}
new HttpServer(port, baseDir).start();
}
public int start() {
isRunning.set(true);
executor.submit(new ServiceListener(port));
return port;
}
public void stop() {
isRunning.set(false);
shutdown(executor);
}
boolean shutdown(final ExecutorService pool) {
pool.shutdown();
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
return false;
}
} catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
if (info) | // Path: src/main/java/cc/agentx/Constants.java
// public final class Constants {
// public static final String APP_NAME = "agentx";
// public static final String APP_VERSION = "1.3";
// public static final String WEB_SERVER_NAME = "agentx-web-console";
//
// private Constants() {
// }
// }
// Path: src/main/java/cc/agentx/ui/HttpServer.java
import cc.agentx.Constants;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
port = getIdlePort();
baseDir = System.getProperty("user.dir").replaceAll("\\\\", "/") + "/www/";
}
new HttpServer(port, baseDir).start();
}
public int start() {
isRunning.set(true);
executor.submit(new ServiceListener(port));
return port;
}
public void stop() {
isRunning.set(false);
shutdown(executor);
}
boolean shutdown(final ExecutorService pool) {
pool.shutdown();
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
return false;
}
} catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
if (info) | System.out.println(Constants.WEB_SERVER_NAME + " stopped."); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/security/BlowfishCipher.java | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.util.KeyHelper;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.engines.BlowfishEngine;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import javax.crypto.spec.SecretKeySpec; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.security;
public class BlowfishCipher extends Cipher {
// encryption mode
public static final int BLOWFISH_CFB = 16;
private final int keyLength;
private final StreamBlockCipher cipher;
/**
* <b>Notice: </b><br>
* 1. in <code>new CFBBlockCipher(engine, <b>8</b> * 8);</code> the IV length (8) is
* reference to the shadowsocks's design.
*
* @see <a href="https://shadowsocks.org/en/spec/cipher.html">
* https://shadowsocks.org/en/spec/cipher.html</a>#Cipher
*/
public BlowfishCipher(String password, int mode) {
key = new SecretKeySpec(password.getBytes(), "BF");
keyLength = mode;
BlowfishEngine engine = new BlowfishEngine();
cipher = new CFBBlockCipher(engine, 8 * 8);
}
public static boolean isValidMode(int mode) {
return mode == 16;
}
@Override
protected void _init(boolean isEncrypt, byte[] iv) {
String keyStr = new String(key.getEncoded());
ParametersWithIV params = new ParametersWithIV( | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/security/BlowfishCipher.java
import cc.agentx.util.KeyHelper;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.engines.BlowfishEngine;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import javax.crypto.spec.SecretKeySpec;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.security;
public class BlowfishCipher extends Cipher {
// encryption mode
public static final int BLOWFISH_CFB = 16;
private final int keyLength;
private final StreamBlockCipher cipher;
/**
* <b>Notice: </b><br>
* 1. in <code>new CFBBlockCipher(engine, <b>8</b> * 8);</code> the IV length (8) is
* reference to the shadowsocks's design.
*
* @see <a href="https://shadowsocks.org/en/spec/cipher.html">
* https://shadowsocks.org/en/spec/cipher.html</a>#Cipher
*/
public BlowfishCipher(String password, int mode) {
key = new SecretKeySpec(password.getBytes(), "BF");
keyLength = mode;
BlowfishEngine engine = new BlowfishEngine();
cipher = new CFBBlockCipher(engine, 8 * 8);
}
public static boolean isValidMode(int mode) {
return mode == 16;
}
@Override
protected void _init(boolean isEncrypt, byte[] iv) {
String keyStr = new String(key.getEncoded());
ParametersWithIV params = new ParametersWithIV( | new KeyParameter(KeyHelper.generateKeyDigest(keyLength, keyStr)), iv |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/client/net/nio/XRelayHandler.java | // Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class XRelayHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final Channel dstChannel; | // Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/client/net/nio/XRelayHandler.java
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.client.net.nio;
public final class XRelayHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log;
static {
log = InternalLoggerFactory.getInstance(XRelayHandler.class);
}
private final Channel dstChannel; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/protocol/request/ShadowsocksRequestResolver.java | // Path: src/main/java/cc/agentx/protocol/Socks5.java
// public class Socks5 {
// public static final int VERSION = 5;
// public static final int ATYP_IPV4 = 1;
// public static final int ATYP_DOMAIN = 3;
// public static final int ATYP_IPV6 = 4;
// // preset replies
// public static byte[] echo = {5, 0};
// public static byte[] reject = {5, (byte) 0xff};
// public static byte[] succeed = {5, 0, 0, 1, 0, 0, 0, 0, 0, 0};
// public static byte[] error_1 = {5, 1, 0, 1, 0, 0, 0, 0, 0, 0}; // general socks server failure
// public static byte[] error_2 = {5, 2, 0, 1, 0, 0, 0, 0, 0, 0}; // connection not allowed by rule set
// public static byte[] error_3 = {5, 3, 0, 1, 0, 0, 0, 0, 0, 0}; // network unreachable
// public static byte[] error_4 = {5, 4, 0, 1, 0, 0, 0, 0, 0, 0}; // host unreachable
// public static byte[] error_5 = {5, 5, 0, 1, 0, 0, 0, 0, 0, 0}; // connection refused
// public static byte[] error_6 = {5, 6, 0, 1, 0, 0, 0, 0, 0, 0}; // ttl expired
// public static byte[] error_7 = {5, 7, 0, 1, 0, 0, 0, 0, 0, 0}; // command not supported
// public static byte[] error_8 = {5, 8, 0, 1, 0, 0, 0, 0, 0, 0}; // address type not supported
// private Socks5() {
// }
//
// }
| import cc.agentx.protocol.Socks5;
import java.util.Arrays; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.protocol.request;
public class ShadowsocksRequestResolver extends XRequestResolver {
public ShadowsocksRequestResolver() {
}
/**
* <pre>
* TCP Request:
* +-------------------+----------------------------+
* | SOCKS5 FIELD (3) | SHADOWSOCKS REQ |
* +-----+-----+-------+------+----------+----------+
* | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
* +-----+-----+-------+------+----------+----------+
* | 1 | 1 | X'00' | 1 | Variable | 2 |
* +-----+-----+-------+------+----------+----------+
*
* UDP Request:
* +-------------------------------------------------------------+
* | AGENTX HEADER |
* +-----+---------------------+---------------------------------------+
* | SOCKS5 FIELD (3) | SHADOWSOCKS REQ |
* +-----+---------------------+------+----------+----------+----------+
* | RSV | FRAG (FAKE-ATYP) | ATYP | DST.ADDR | DST.PORT | DATA |
* +----+----------------------+------+----------+----------+----------+
* | 2 | X'00' | 1 | Variable | 2 | Variable |
* +-----+---------------------+------+----------+----------+----------+
* </pre>
* Notice: In AgentX implementation, we send udp traffic though a secure tcp tunnel,
* to distinct these two types of tcp payload, we add an extra 0 byte in front of any
* udp-target requests. Thus, if we find a ATYP equals to 0, after truncate the first
* byte, we can get the accurate udp-target request.
*/
@Override
public byte[] wrap(XRequest.Channel channel, final byte[] bytes) {
if (channel == XRequest.Channel.UDP)
return Arrays.copyOfRange(bytes, 2, bytes.length);
else
return Arrays.copyOfRange(bytes, 3, bytes.length);
}
@Override
public XRequest parse(byte[] bytes) {
boolean udp = false;
XRequest.Type atyp;
String host;
int port, subsequentDataLength;
// mark udp payload
if (bytes[0] == 0) {
udp = true;
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
switch (bytes[0]) { | // Path: src/main/java/cc/agentx/protocol/Socks5.java
// public class Socks5 {
// public static final int VERSION = 5;
// public static final int ATYP_IPV4 = 1;
// public static final int ATYP_DOMAIN = 3;
// public static final int ATYP_IPV6 = 4;
// // preset replies
// public static byte[] echo = {5, 0};
// public static byte[] reject = {5, (byte) 0xff};
// public static byte[] succeed = {5, 0, 0, 1, 0, 0, 0, 0, 0, 0};
// public static byte[] error_1 = {5, 1, 0, 1, 0, 0, 0, 0, 0, 0}; // general socks server failure
// public static byte[] error_2 = {5, 2, 0, 1, 0, 0, 0, 0, 0, 0}; // connection not allowed by rule set
// public static byte[] error_3 = {5, 3, 0, 1, 0, 0, 0, 0, 0, 0}; // network unreachable
// public static byte[] error_4 = {5, 4, 0, 1, 0, 0, 0, 0, 0, 0}; // host unreachable
// public static byte[] error_5 = {5, 5, 0, 1, 0, 0, 0, 0, 0, 0}; // connection refused
// public static byte[] error_6 = {5, 6, 0, 1, 0, 0, 0, 0, 0, 0}; // ttl expired
// public static byte[] error_7 = {5, 7, 0, 1, 0, 0, 0, 0, 0, 0}; // command not supported
// public static byte[] error_8 = {5, 8, 0, 1, 0, 0, 0, 0, 0, 0}; // address type not supported
// private Socks5() {
// }
//
// }
// Path: src/main/java/cc/agentx/protocol/request/ShadowsocksRequestResolver.java
import cc.agentx.protocol.Socks5;
import java.util.Arrays;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.protocol.request;
public class ShadowsocksRequestResolver extends XRequestResolver {
public ShadowsocksRequestResolver() {
}
/**
* <pre>
* TCP Request:
* +-------------------+----------------------------+
* | SOCKS5 FIELD (3) | SHADOWSOCKS REQ |
* +-----+-----+-------+------+----------+----------+
* | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
* +-----+-----+-------+------+----------+----------+
* | 1 | 1 | X'00' | 1 | Variable | 2 |
* +-----+-----+-------+------+----------+----------+
*
* UDP Request:
* +-------------------------------------------------------------+
* | AGENTX HEADER |
* +-----+---------------------+---------------------------------------+
* | SOCKS5 FIELD (3) | SHADOWSOCKS REQ |
* +-----+---------------------+------+----------+----------+----------+
* | RSV | FRAG (FAKE-ATYP) | ATYP | DST.ADDR | DST.PORT | DATA |
* +----+----------------------+------+----------+----------+----------+
* | 2 | X'00' | 1 | Variable | 2 | Variable |
* +-----+---------------------+------+----------+----------+----------+
* </pre>
* Notice: In AgentX implementation, we send udp traffic though a secure tcp tunnel,
* to distinct these two types of tcp payload, we add an extra 0 byte in front of any
* udp-target requests. Thus, if we find a ATYP equals to 0, after truncate the first
* byte, we can get the accurate udp-target request.
*/
@Override
public byte[] wrap(XRequest.Channel channel, final byte[] bytes) {
if (channel == XRequest.Channel.UDP)
return Arrays.copyOfRange(bytes, 2, bytes.length);
else
return Arrays.copyOfRange(bytes, 3, bytes.length);
}
@Override
public XRequest parse(byte[] bytes) {
boolean udp = false;
XRequest.Type atyp;
String host;
int port, subsequentDataLength;
// mark udp payload
if (bytes[0] == 0) {
udp = true;
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
switch (bytes[0]) { | case Socks5.ATYP_IPV4: |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/wrapper/CipherWrapper.java | // Path: src/main/java/cc/agentx/security/Cipher.java
// public abstract class Cipher {
// protected SecretKey key;
// protected byte[] iv;
// protected boolean isEncrypt;
//
// public void init(boolean isEncrypt, byte[] iv) {
// if (this.iv == null) {
// this.isEncrypt = isEncrypt;
// this.iv = iv;
// _init(isEncrypt, iv);
// } else {
// throw new RuntimeException("cipher cannot reinitiate");
// }
// }
//
// public byte[] encrypt(byte[] originData) {
// if (this.iv == null)
// throw new CipherNotInitializedException();
// if (!isEncrypt)
// throw new RuntimeException("cannot encrypt in decrypt mode");
// return _encrypt(originData);
// }
//
// public byte[] decrypt(byte[] encryptedData) {
// if (this.iv == null)
// throw new CipherNotInitializedException();
// if (isEncrypt)
// throw new RuntimeException("cannot decrypt in encrypt mode");
// return _decrypt(encryptedData);
// }
//
// public SecretKey getKey() {
// return key;
// }
//
// public byte[] getIV() {
// return iv;
// }
//
// public abstract int getIVLength();
//
// protected abstract void _init(boolean isEncrypt, byte[] iv);
//
// protected abstract byte[] _encrypt(final byte[] originData);
//
// protected abstract byte[] _decrypt(final byte[] encryptedData);
//
// }
//
// Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.security.Cipher;
import cc.agentx.util.KeyHelper;
import java.util.Arrays; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class CipherWrapper extends Wrapper {
private final Cipher encipher;
private final Cipher decipher;
private byte[] encipherIv;
private byte[] decipherIv;
public CipherWrapper(Cipher encipher, Cipher decipher) {
if (encipher.getClass() != decipher.getClass())
throw new RuntimeException("cipher type not match");
this.encipher = encipher;
this.decipher = decipher;
}
@Override
public byte[] wrap(final byte[] bytes) {
if (encipherIv == null) {
int ivLength = encipher.getIVLength(); | // Path: src/main/java/cc/agentx/security/Cipher.java
// public abstract class Cipher {
// protected SecretKey key;
// protected byte[] iv;
// protected boolean isEncrypt;
//
// public void init(boolean isEncrypt, byte[] iv) {
// if (this.iv == null) {
// this.isEncrypt = isEncrypt;
// this.iv = iv;
// _init(isEncrypt, iv);
// } else {
// throw new RuntimeException("cipher cannot reinitiate");
// }
// }
//
// public byte[] encrypt(byte[] originData) {
// if (this.iv == null)
// throw new CipherNotInitializedException();
// if (!isEncrypt)
// throw new RuntimeException("cannot encrypt in decrypt mode");
// return _encrypt(originData);
// }
//
// public byte[] decrypt(byte[] encryptedData) {
// if (this.iv == null)
// throw new CipherNotInitializedException();
// if (isEncrypt)
// throw new RuntimeException("cannot decrypt in encrypt mode");
// return _decrypt(encryptedData);
// }
//
// public SecretKey getKey() {
// return key;
// }
//
// public byte[] getIV() {
// return iv;
// }
//
// public abstract int getIVLength();
//
// protected abstract void _init(boolean isEncrypt, byte[] iv);
//
// protected abstract byte[] _encrypt(final byte[] originData);
//
// protected abstract byte[] _decrypt(final byte[] encryptedData);
//
// }
//
// Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/wrapper/CipherWrapper.java
import cc.agentx.security.Cipher;
import cc.agentx.util.KeyHelper;
import java.util.Arrays;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class CipherWrapper extends Wrapper {
private final Cipher encipher;
private final Cipher decipher;
private byte[] encipherIv;
private byte[] decipherIv;
public CipherWrapper(Cipher encipher, Cipher decipher) {
if (encipher.getClass() != decipher.getClass())
throw new RuntimeException("cipher type not match");
this.encipher = encipher;
this.decipher = decipher;
}
@Override
public byte[] wrap(final byte[] bytes) {
if (encipherIv == null) {
int ivLength = encipher.getIVLength(); | this.encipherIv = KeyHelper.generateRandomBytes(ivLength); |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/net/nio/XRelayHandler.java | // Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
| import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class XRelayHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log = InternalLoggerFactory.getInstance(XRelayHandler.class);
private final Channel dstChannel; | // Path: src/main/java/cc/agentx/wrapper/Wrapper.java
// public abstract class Wrapper implements Parcelable {
//
// }
// Path: src/main/java/cc/agentx/server/net/nio/XRelayHandler.java
import cc.agentx.wrapper.Wrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server.net.nio;
public final class XRelayHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log = InternalLoggerFactory.getInstance(XRelayHandler.class);
private final Channel dstChannel; | private final Wrapper wrapper; |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/wrapper/RandomPaddingWrapper.java | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
| import cc.agentx.util.KeyHelper;
import java.util.Arrays; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class RandomPaddingWrapper extends PaddingWrapper {
public RandomPaddingWrapper(int paddingThreshold, int paddingRange) {
super(paddingThreshold, paddingRange);
if (paddingThreshold + paddingRange < 0xFF - 1)
headerLength = 1;
else if (paddingThreshold + paddingRange < 0xFFFF - 2)
headerLength = 2;
else if (paddingThreshold + paddingRange < 0xFFFFFF - 3)
headerLength = 3;
}
@Override
public byte[] wrap(byte[] bytes) {
if (bytes.length < paddingThreshold + paddingRange) { | // Path: src/main/java/cc/agentx/util/KeyHelper.java
// public class KeyHelper {
// private static SecureRandom randomizer = new SecureRandom();
//
// private KeyHelper() {
// }
//
// public static int generateRandomInteger(int min, int max) {
// return min + randomizer.nextInt(max - min);
// }
//
// public static byte[] generateRandomBytes(int length) {
// byte[] bytes = new byte[length];
// randomizer.nextBytes(bytes);
// return bytes;
// }
//
// public static byte[] generateKeyDigest(int keyLength, String password) {
// try {
// MessageDigest digester = MessageDigest.getInstance("MD5");
// int length = (keyLength + 15) / 16 * 16;
// byte[] passwordBytes = password.getBytes("UTF-8");
// byte[] temp = digester.digest(passwordBytes);
// byte[] key = Arrays.copyOf(temp, length);
// for (int i = 1; i < length / 16; i++) {
// temp = Arrays.copyOf(temp, 16 + passwordBytes.length);
// System.arraycopy(passwordBytes, 0, temp, 16, passwordBytes.length);
// System.arraycopy(digester.digest(temp), 0, key, i * 16, 16);
// }
// return Arrays.copyOf(key, keyLength);
// } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// return new byte[keyLength];
// }
//
// public static byte[] getCompressedBytes(int value) {
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0)
// return Arrays.copyOfRange(bytes, 3, 4);
// if (bytes[0] == 0 && bytes[1] == 0)
// return Arrays.copyOfRange(bytes, 2, 4);
// if (bytes[0] == 0)
// return Arrays.copyOfRange(bytes, 1, 4);
// return bytes;
// }
//
// public static byte[] getBytes(int length, int value) {
// if (length < 1 || length > 4)
// throw new RuntimeException("bad length");
// byte[] bytes = new byte[4];
// bytes[0] = (byte) ((value >> 24) & 0xff);
// bytes[1] = (byte) ((value >> 16) & 0xff);
// bytes[2] = (byte) ((value >> 8) & 0xff);
// bytes[3] = (byte) (value & 0xff);
// if (length == 4)
// return bytes;
// else
// return Arrays.copyOfRange(bytes, 4 - length, 4);
// }
//
// public static byte[] getBytes(int value) {
// return getBytes(4, value);
// }
//
// public static int toBigEndianInteger(byte[] bytes) {
// byte[] value = new byte[4];
// System.arraycopy(bytes, 0, value, 4 - bytes.length, bytes.length);
// return (value[0] & 0xff) << 24 | (value[1] & 0xff) << 16
// | (value[2] & 0xff) << 8 | (value[3] & 0xff);
// }
//
// public int getRandomIdentifier(int length) {
// int base = (int) Math.pow(10, length - 1);
// return randomizer.nextInt(base * 9) + base;
// }
// }
// Path: src/main/java/cc/agentx/wrapper/RandomPaddingWrapper.java
import cc.agentx.util.KeyHelper;
import java.util.Arrays;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.wrapper;
public class RandomPaddingWrapper extends PaddingWrapper {
public RandomPaddingWrapper(int paddingThreshold, int paddingRange) {
super(paddingThreshold, paddingRange);
if (paddingThreshold + paddingRange < 0xFF - 1)
headerLength = 1;
else if (paddingThreshold + paddingRange < 0xFFFF - 2)
headerLength = 2;
else if (paddingThreshold + paddingRange < 0xFFFFFF - 3)
headerLength = 3;
}
@Override
public byte[] wrap(byte[] bytes) {
if (bytes.length < paddingThreshold + paddingRange) { | int randomLength = KeyHelper.generateRandomInteger( |
ZhangJiupeng/AgentX | src/main/java/cc/agentx/server/Main.java | // Path: src/main/java/cc/agentx/server/net/nio/XServer.java
// public final class XServer {
// private static final InternalLogger log = InternalLoggerFactory.getInstance(XServer.class);
//
// private XServer() {
// }
//
// public static XServer getInstance() {
// return new XServer();
// }
//
// public void start() {
// Configuration config = Configuration.INSTANCE;
// InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
// EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// EventLoopGroup workerGroup = new NioEventLoopGroup();
// try {
// ServerBootstrap bootstrap = new ServerBootstrap();
// bootstrap.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// .childHandler(new ChannelInitializer<SocketChannel>() {
// protected void initChannel(SocketChannel socketChannel) throws Exception {
// socketChannel.pipeline()
// .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
// .addLast(new XConnectHandler());
// if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
// socketChannel.pipeline().addLast(
// new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())
// );
// }
// }
// });
// log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol());
// new Thread(() -> new UdpServer().start()).start();
// ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
// future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort()));
// future.channel().closeFuture().sync();
// } catch (Exception e) {
// log.error("\tSocket bind failure ({})", e.getMessage());
// } finally {
// log.info("\tShutting down and recycling...");
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// Configuration.shutdownRelays();
// }
// System.exit(0);
// }
// }
| import cc.agentx.server.net.nio.XServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void init() {
try {
Configuration.init();
} catch (Exception e) {
log.error("\tInitialization failed ({})", e.getMessage());
System.exit(-1);
}
}
public static void main(String[] args) {
Main.init(); | // Path: src/main/java/cc/agentx/server/net/nio/XServer.java
// public final class XServer {
// private static final InternalLogger log = InternalLoggerFactory.getInstance(XServer.class);
//
// private XServer() {
// }
//
// public static XServer getInstance() {
// return new XServer();
// }
//
// public void start() {
// Configuration config = Configuration.INSTANCE;
// InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
// EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// EventLoopGroup workerGroup = new NioEventLoopGroup();
// try {
// ServerBootstrap bootstrap = new ServerBootstrap();
// bootstrap.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// .childHandler(new ChannelInitializer<SocketChannel>() {
// protected void initChannel(SocketChannel socketChannel) throws Exception {
// socketChannel.pipeline()
// .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
// .addLast(new XConnectHandler());
// if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
// socketChannel.pipeline().addLast(
// new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())
// );
// }
// }
// });
// log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol());
// new Thread(() -> new UdpServer().start()).start();
// ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
// future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort()));
// future.channel().closeFuture().sync();
// } catch (Exception e) {
// log.error("\tSocket bind failure ({})", e.getMessage());
// } finally {
// log.info("\tShutting down and recycling...");
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// Configuration.shutdownRelays();
// }
// System.exit(0);
// }
// }
// Path: src/main/java/cc/agentx/server/Main.java
import cc.agentx.server.net.nio.XServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright 2017 ZhangJiupeng
*
* 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 cc.agentx.server;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void init() {
try {
Configuration.init();
} catch (Exception e) {
log.error("\tInitialization failed ({})", e.getMessage());
System.exit(-1);
}
}
public static void main(String[] args) {
Main.init(); | XServer.getInstance().start(); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/CalculatorSettings.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
| import android.content.Context;
import android.preference.PreferenceManager;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel; | package com.gigabytedevelopersinc.app.calculator;
public class CalculatorSettings {
static boolean graphPanel(Context context) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/CalculatorSettings.java
import android.content.Context;
import android.preference.PreferenceManager;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel;
package com.gigabytedevelopersinc.app.calculator;
public class CalculatorSettings {
static boolean graphPanel(Context context) { | return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Panel.GRAPH.toString(), context.getResources().getBoolean(R.bool.GRAPH)); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/Persist.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/BaseModule.java
// public enum Mode {
// BINARY(0), DECIMAL(1), HEXADECIMAL(2);
//
// int quickSerializable;
//
// Mode(int num) {
// this.quickSerializable = num;
// }
//
// public int getQuickSerializable() {
// return quickSerializable;
// }
// }
| import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import com.gigabytedevelopersinc.app.calculator.BaseModule.Mode; |
package com.gigabytedevelopersinc.app.calculator;
class Persist {
private static final int LAST_VERSION = 3;
private static final String FILE_NAME = "calculator.data";
private Context mContext;
History history = new History();
private int mDeleteMode; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/BaseModule.java
// public enum Mode {
// BINARY(0), DECIMAL(1), HEXADECIMAL(2);
//
// int quickSerializable;
//
// Mode(int num) {
// this.quickSerializable = num;
// }
//
// public int getQuickSerializable() {
// return quickSerializable;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Persist.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import com.gigabytedevelopersinc.app.calculator.BaseModule.Mode;
package com.gigabytedevelopersinc.app.calculator;
class Persist {
private static final int LAST_VERSION = 3;
private static final String FILE_NAME = "calculator.data";
private Context mContext;
History history = new History();
private int mDeleteMode; | private Mode mode; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java
// public class HistoryLine extends LinearLayout {
// private static final int COPY = 0;
// private static final int COPY_BASE = 1;
// private static final int COPY_EDITED = 2;
// private static final int REMOVE = 3;
// private String[] mMenuItemsStrings;
// private HistoryEntry mHistoryEntry;
// private History mHistory;
// private BaseAdapter mAdapter;
//
// public HistoryLine(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override
// public void onCreateContextMenu(ContextMenu menu) {
// MenuHandler handler = new MenuHandler();
// if(mMenuItemsStrings == null) {
// Resources resources = getResources();
// mMenuItemsStrings = new String[4];
// mMenuItemsStrings[COPY] = String.format(resources.getString(R.string.copy), mHistoryEntry.getBase() + "=" + mHistoryEntry.getEdited());
// mMenuItemsStrings[COPY_BASE] = String.format(resources.getString(R.string.copy), mHistoryEntry.getBase());
// mMenuItemsStrings[COPY_EDITED] = String.format(resources.getString(R.string.copy), mHistoryEntry.getEdited());
// mMenuItemsStrings[REMOVE] = resources.getString(R.string.remove_from_history);
// }
// for(int i = 0; i < mMenuItemsStrings.length; i++) {
// menu.add(Menu.NONE, i, i, mMenuItemsStrings[i]).setOnMenuItemClickListener(handler);
// }
// }
//
// private class MenuHandler implements MenuItem.OnMenuItemClickListener {
// public boolean onMenuItemClick(MenuItem item) {
// return onTextContextMenuItem(item.getTitle());
// }
// }
//
// public boolean onTextContextMenuItem(CharSequence title) {
// boolean handled = false;
// if(TextUtils.equals(title, mMenuItemsStrings[COPY])) {
// copyContent(mHistoryEntry.getBase() + "=" + mHistoryEntry.getEdited());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[COPY_BASE])) {
// copyContent(mHistoryEntry.getBase());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[COPY_EDITED])) {
// copyContent(mHistoryEntry.getEdited());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[REMOVE])) {
// removeContent();
// handled = true;
// }
// return handled;
// }
//
// public void copyContent(String content) {
// ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
// clipboard.setPrimaryClip(ClipData.newPlainText(null, content));
// String toastText = String.format(getResources().getString(R.string.text_copied_toast), content);
// Toast.makeText(getContext(), toastText, Toast.LENGTH_SHORT).show();
// }
//
// private void removeContent() {
// mHistory.remove(mHistoryEntry);
// mAdapter.notifyDataSetChanged();
// }
//
// public HistoryEntry getHistoryEntry() {
// return mHistoryEntry;
// }
//
// public void setHistoryEntry(HistoryEntry historyEntry) {
// this.mHistoryEntry = historyEntry;
// }
//
// public History getHistory() {
// return mHistory;
// }
//
// public void setHistory(History history) {
// this.mHistory = history;
// }
//
// public BaseAdapter getAdapter() {
// return mAdapter;
// }
//
// public void setAdapter(BaseAdapter adapter) {
// this.mAdapter = adapter;
// }
//
// public void showMenu() {
// showContextMenu();
// }
// }
| import java.util.Vector;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.gigabytedevelopersinc.app.calculator.view.HistoryLine; |
package com.gigabytedevelopersinc.app.calculator;
class HistoryAdapter extends BaseAdapter {
private final Vector<HistoryEntry> mEntries;
private final LayoutInflater mInflater;
private final EquationFormatter mEquationFormatter;
private final History mHistory;
HistoryAdapter(Context context, History history) {
mEntries = history.mEntries;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mEquationFormatter = new EquationFormatter();
mHistory = history;
}
@Override
public int getCount() {
return mEntries.size() - 1;
}
@Override
public Object getItem(int position) {
return mEntries.elementAt(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java
// public class HistoryLine extends LinearLayout {
// private static final int COPY = 0;
// private static final int COPY_BASE = 1;
// private static final int COPY_EDITED = 2;
// private static final int REMOVE = 3;
// private String[] mMenuItemsStrings;
// private HistoryEntry mHistoryEntry;
// private History mHistory;
// private BaseAdapter mAdapter;
//
// public HistoryLine(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// @Override
// public void onCreateContextMenu(ContextMenu menu) {
// MenuHandler handler = new MenuHandler();
// if(mMenuItemsStrings == null) {
// Resources resources = getResources();
// mMenuItemsStrings = new String[4];
// mMenuItemsStrings[COPY] = String.format(resources.getString(R.string.copy), mHistoryEntry.getBase() + "=" + mHistoryEntry.getEdited());
// mMenuItemsStrings[COPY_BASE] = String.format(resources.getString(R.string.copy), mHistoryEntry.getBase());
// mMenuItemsStrings[COPY_EDITED] = String.format(resources.getString(R.string.copy), mHistoryEntry.getEdited());
// mMenuItemsStrings[REMOVE] = resources.getString(R.string.remove_from_history);
// }
// for(int i = 0; i < mMenuItemsStrings.length; i++) {
// menu.add(Menu.NONE, i, i, mMenuItemsStrings[i]).setOnMenuItemClickListener(handler);
// }
// }
//
// private class MenuHandler implements MenuItem.OnMenuItemClickListener {
// public boolean onMenuItemClick(MenuItem item) {
// return onTextContextMenuItem(item.getTitle());
// }
// }
//
// public boolean onTextContextMenuItem(CharSequence title) {
// boolean handled = false;
// if(TextUtils.equals(title, mMenuItemsStrings[COPY])) {
// copyContent(mHistoryEntry.getBase() + "=" + mHistoryEntry.getEdited());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[COPY_BASE])) {
// copyContent(mHistoryEntry.getBase());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[COPY_EDITED])) {
// copyContent(mHistoryEntry.getEdited());
// handled = true;
// }
// else if(TextUtils.equals(title, mMenuItemsStrings[REMOVE])) {
// removeContent();
// handled = true;
// }
// return handled;
// }
//
// public void copyContent(String content) {
// ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
// clipboard.setPrimaryClip(ClipData.newPlainText(null, content));
// String toastText = String.format(getResources().getString(R.string.text_copied_toast), content);
// Toast.makeText(getContext(), toastText, Toast.LENGTH_SHORT).show();
// }
//
// private void removeContent() {
// mHistory.remove(mHistoryEntry);
// mAdapter.notifyDataSetChanged();
// }
//
// public HistoryEntry getHistoryEntry() {
// return mHistoryEntry;
// }
//
// public void setHistoryEntry(HistoryEntry historyEntry) {
// this.mHistoryEntry = historyEntry;
// }
//
// public History getHistory() {
// return mHistory;
// }
//
// public void setHistory(History history) {
// this.mHistory = history;
// }
//
// public BaseAdapter getAdapter() {
// return mAdapter;
// }
//
// public void setAdapter(BaseAdapter adapter) {
// this.mAdapter = adapter;
// }
//
// public void showMenu() {
// showContextMenu();
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryAdapter.java
import java.util.Vector;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.gigabytedevelopersinc.app.calculator.view.HistoryLine;
package com.gigabytedevelopersinc.app.calculator;
class HistoryAdapter extends BaseAdapter {
private final Vector<HistoryEntry> mEntries;
private final LayoutInflater mInflater;
private final EquationFormatter mEquationFormatter;
private final History mHistory;
HistoryAdapter(Context context, History history) {
mEntries = history.mEntries;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mEquationFormatter = new EquationFormatter();
mHistory = history;
}
@Override
public int getCount() {
return mEntries.size() - 1;
}
@Override
public Object getItem(int position) {
return mEntries.elementAt(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) { | HistoryLine view; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/About.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/AboutFragment.java
// public class AboutFragment extends PreferenceFragment {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.about);
// Preference about = findPreference("ABOUT");
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// }
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.gigabytedevelopersinc.app.calculator.view.AboutFragment; | package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class About extends Activity {
//Create New Variable of type InterstitialAd
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/AboutFragment.java
// public class AboutFragment extends PreferenceFragment {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.about);
// Preference about = findPreference("ABOUT");
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// }
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/About.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.gigabytedevelopersinc.app.calculator.view.AboutFragment;
package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class About extends Activity {
//Create New Variable of type InterstitialAd
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | AboutFragment about = new AboutFragment(); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/Preferences.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/PreferencesFragment.java
// public class PreferencesFragment extends PreferenceFragment {
//
// //Create New Variable of type InterstitialAd
// private InterstitialAd mInterstitialAd;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.preferences);
// Preference about = findPreference("ABOUT");
//
// // Prepare the interstitial Ad
// mInterstitialAd = new InterstitialAd(getActivity());
// // Insert the Ad Unit ID
// mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ads));
// AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .build();
// // Load requested Ad
// mInterstitialAd.loadAd(adRequest);
//
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
// @Override
// public boolean onPreferenceClick(Preference preference) {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// mInterstitialAd.setAdListener(new AdListener() {
// public void onAdClosed() {
// AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .build();
// mInterstitialAd.loadAd(adRequest);
// Intent github = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/gigabytedevelopers/CalcMate"));
// startActivity(github);
//
// }
// });
// } else {
// Intent github = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/gigabytedevelopers/CalcMate"));
// startActivity(github);
// }
// return false;
// }
// });
// }
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import com.gigabytedevelopersinc.app.calculator.view.PreferencesFragment; | package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class Preferences extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/PreferencesFragment.java
// public class PreferencesFragment extends PreferenceFragment {
//
// //Create New Variable of type InterstitialAd
// private InterstitialAd mInterstitialAd;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.preferences);
// Preference about = findPreference("ABOUT");
//
// // Prepare the interstitial Ad
// mInterstitialAd = new InterstitialAd(getActivity());
// // Insert the Ad Unit ID
// mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ads));
// AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .build();
// // Load requested Ad
// mInterstitialAd.loadAd(adRequest);
//
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
// @Override
// public boolean onPreferenceClick(Preference preference) {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// mInterstitialAd.setAdListener(new AdListener() {
// public void onAdClosed() {
// AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .build();
// mInterstitialAd.loadAd(adRequest);
// Intent github = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/gigabytedevelopers/CalcMate"));
// startActivity(github);
//
// }
// });
// } else {
// Intent github = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/gigabytedevelopers/CalcMate"));
// startActivity(github);
// }
// return false;
// }
// });
// }
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Preferences.java
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import com.gigabytedevelopersinc.app.calculator.view.PreferencesFragment;
package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class Preferences extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | PreferencesFragment preferences = new PreferencesFragment(); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/LargePageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum LargePanel {
// GRAPH, BASIC, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.LargePanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | package com.gigabytedevelopersinc.app.calculator;
public class LargePageAdapter extends PagerAdapter {
private View mGraphPage;
private View mSimplePage;
View mMatrixPage; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum LargePanel {
// GRAPH, BASIC, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/LargePageAdapter.java
import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.LargePanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
package com.gigabytedevelopersinc.app.calculator;
public class LargePageAdapter extends PagerAdapter {
private View mGraphPage;
private View mSimplePage;
View mMatrixPage; | private CalculatorViewPager mParent; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/LargePageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum LargePanel {
// GRAPH, BASIC, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.LargePanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | setOrder();
switch(mLogic.mBaseModule.getMode()) {
case BINARY:
for(int i : mLogic.mBaseModule.bannedResourceInBinary) {
View v = mSimplePage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case DECIMAL:
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mSimplePage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case HEXADECIMAL:
break;
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum LargePanel {
// GRAPH, BASIC, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/LargePageAdapter.java
import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.LargePanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
setOrder();
switch(mLogic.mBaseModule.getMode()) {
case BINARY:
for(int i : mLogic.mBaseModule.bannedResourceInBinary) {
View v = mSimplePage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case DECIMAL:
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mSimplePage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case HEXADECIMAL:
break;
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | if(position == LargePanel.GRAPH.getOrder() && CalculatorSettings.graphPanel(mParent.getContext())) { |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/Help.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HelpFragment.java
// public class HelpFragment extends PreferenceFragment {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.help);
// Preference about = findPreference("ABOUT");
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// }
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import com.gigabytedevelopersinc.app.calculator.view.HelpFragment; | package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class Help extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HelpFragment.java
// public class HelpFragment extends PreferenceFragment {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.layout.help);
// Preference about = findPreference("ABOUT");
// if(about != null) {
// String versionName = "";
// try {
// versionName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
// }
// catch(NameNotFoundException e) {
// e.printStackTrace();
// }
// about.setTitle(about.getTitle() + " " + versionName);
// }
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Help.java
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import com.gigabytedevelopersinc.app.calculator.view.HelpFragment;
package com.gigabytedevelopersinc.app.calculator;
/**
* @author Emmanuel Nwokoma (Founder and CEO of Gigabyte Developers INC)
**/
public class Help extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getActionBar() != null)
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
if(savedInstanceState == null) { | HelpFragment help = new HelpFragment(); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/CalculatorWidget.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/BaseModule.java
// public enum Mode {
// BINARY(0), DECIMAL(1), HEXADECIMAL(2);
//
// int quickSerializable;
//
// Mode(int num) {
// this.quickSerializable = num;
// }
//
// public int getQuickSerializable() {
// return quickSerializable;
// }
// }
| import org.javia.arity.SyntaxException;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;
import com.gigabytedevelopersinc.app.calculator.BaseModule.Mode; | else if(intent.getAction().equals(DIV)) {
value += context.getResources().getString(R.string.div);
}
else if(intent.getAction().equals(MUL)) {
value += context.getResources().getString(R.string.mul);
}
else if(intent.getAction().equals(MINUS)) {
value += context.getResources().getString(R.string.minus);
}
else if(intent.getAction().equals(PLUS)) {
value += context.getResources().getString(R.string.plus);
}
else if(intent.getAction().equals(EQUALS)) {
final String input = value;
if(input.isEmpty()) return;
final Logic mLogic = new Logic(context, null, null);
mLogic.setLineLength(7);
try {
value = mLogic.evaluate(input);
}
catch(SyntaxException e) {
value = context.getResources().getString(R.string.error);
}
// Try to save it to history
if(!value.equals(context.getResources().getString(R.string.error))) {
final Persist persist = new Persist(context);
persist.load(); | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/BaseModule.java
// public enum Mode {
// BINARY(0), DECIMAL(1), HEXADECIMAL(2);
//
// int quickSerializable;
//
// Mode(int num) {
// this.quickSerializable = num;
// }
//
// public int getQuickSerializable() {
// return quickSerializable;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/CalculatorWidget.java
import org.javia.arity.SyntaxException;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;
import com.gigabytedevelopersinc.app.calculator.BaseModule.Mode;
else if(intent.getAction().equals(DIV)) {
value += context.getResources().getString(R.string.div);
}
else if(intent.getAction().equals(MUL)) {
value += context.getResources().getString(R.string.mul);
}
else if(intent.getAction().equals(MINUS)) {
value += context.getResources().getString(R.string.minus);
}
else if(intent.getAction().equals(PLUS)) {
value += context.getResources().getString(R.string.plus);
}
else if(intent.getAction().equals(EQUALS)) {
final String input = value;
if(input.isEmpty()) return;
final Logic mLogic = new Logic(context, null, null);
mLogic.setLineLength(7);
try {
value = mLogic.evaluate(input);
}
catch(SyntaxException e) {
value = context.getResources().getString(R.string.error);
}
// Try to save it to history
if(!value.equals(context.getResources().getString(R.string.error))) {
final Persist persist = new Persist(context);
persist.load(); | if(persist.getMode() == null) persist.setMode(Mode.DECIMAL); |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/PageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | package com.gigabytedevelopersinc.app.calculator;
public class PageAdapter extends PagerAdapter {
private View mGraphPage;
private View mFunctionPage;
private View mSimplePage;
private View mAdvancedPage;
private View mHexPage;
View mMatrixPage; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/PageAdapter.java
import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
package com.gigabytedevelopersinc.app.calculator;
public class PageAdapter extends PagerAdapter {
private View mGraphPage;
private View mFunctionPage;
private View mSimplePage;
private View mAdvancedPage;
private View mHexPage;
View mMatrixPage; | private CalculatorViewPager mParent; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/PageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | case DECIMAL:
mHexPage.findViewById(R.id.dec).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mSimplePage.findViewById(i);
if(v == null) v = mHexPage.findViewById(i);
v.setEnabled(false);
}
break;
case HEXADECIMAL:
mHexPage.findViewById(R.id.hex).setBackgroundResource(R.color.pressed_color);
break;
}
View easterEgg = mMatrixPage.findViewById(R.id.easter);
if(easterEgg != null) {
easterEgg.setOnClickListener(listener);
easterEgg.setOnLongClickListener(listener);
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum Panel {
// GRAPH, FUNCTION, HEX, BASIC, ADVANCED, MATRIX;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/PageAdapter.java
import org.achartengine.GraphicalView;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.gigabytedevelopersinc.app.calculator.Calculator.Panel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
case DECIMAL:
mHexPage.findViewById(R.id.dec).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mSimplePage.findViewById(i);
if(v == null) v = mHexPage.findViewById(i);
v.setEnabled(false);
}
break;
case HEXADECIMAL:
mHexPage.findViewById(R.id.hex).setBackgroundResource(R.color.pressed_color);
break;
}
View easterEgg = mMatrixPage.findViewById(R.id.easter);
if(easterEgg != null) {
easterEgg.setOnClickListener(listener);
easterEgg.setOnLongClickListener(listener);
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | if(position == Panel.GRAPH.getOrder() && CalculatorSettings.graphPanel(mParent.getContext())) { |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/ui/AdWrapper.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public static boolean isTelevision() {
// return isTelevision;
// }
| import android.content.Context;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.gigabytedevelopersinc.app.calculator.R;
import static com.gigabytedevelopersinc.app.calculator.Calculator.isTelevision; | package com.gigabytedevelopersinc.app.calculator.ui;
/**
* A Wrapper which wraps AdView along with loading the view aswell
*/
public class AdWrapper extends FrameLayout {
private AdView mAdView;
private InterstitialAd mInterstitialAd;
private boolean showInterstiatial = true;
public AdWrapper(Context context) {
super(context);
init(context);
}
public AdWrapper(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public AdWrapper(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
//Ads | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public static boolean isTelevision() {
// return isTelevision;
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/ui/AdWrapper.java
import android.content.Context;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.gigabytedevelopersinc.app.calculator.R;
import static com.gigabytedevelopersinc.app.calculator.Calculator.isTelevision;
package com.gigabytedevelopersinc.app.calculator.ui;
/**
* A Wrapper which wraps AdView along with loading the view aswell
*/
public class AdWrapper extends FrameLayout {
private AdView mAdView;
private InterstitialAd mInterstitialAd;
private boolean showInterstiatial = true;
public AdWrapper(Context context) {
super(context);
init(context);
}
public AdWrapper(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public AdWrapper(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
//Ads | if(!isTelevision()){ |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/MatrixInverseView.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/MutableString.java
// public class MutableString {
// private String text;
//
// public MutableString() {
//
// }
//
// public MutableString(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public int length() {
// return text.length();
// }
//
// public boolean isEmpty() {
// return text.isEmpty();
// }
//
// public String substring(int start) {
// return text.substring(start);
// }
//
// public String substring(int start, int end) {
// return text.substring(start, end);
// }
//
// public CharSequence subSequence(int start, int end) {
// return text.subSequence(start, end);
// }
//
// public boolean startsWith(String prefix) {
// return text.startsWith(prefix);
// }
// }
| import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.InputType;
import com.gigabytedevelopersinc.app.calculator.MutableString;
import com.gigabytedevelopersinc.app.calculator.R; |
package com.gigabytedevelopersinc.app.calculator.view;
public class MatrixInverseView extends AppCompatTextView {
private final static char PLACEHOLDER = '\uFEFF';
public final static String PATTERN = PLACEHOLDER + "^-1";
public MatrixInverseView(Context context) {
super(context);
}
public MatrixInverseView(final AdvancedDisplay display) {
super(display.getContext());
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setText(Html.fromHtml("<sup><small>-1</small></sup>"));
setTextAppearance(display.getContext(), R.style.display_style);
setPadding(0, 0, 0, 0);
}
@Override
public String toString() {
return PATTERN;
}
| // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/MutableString.java
// public class MutableString {
// private String text;
//
// public MutableString() {
//
// }
//
// public MutableString(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public int length() {
// return text.length();
// }
//
// public boolean isEmpty() {
// return text.isEmpty();
// }
//
// public String substring(int start) {
// return text.substring(start);
// }
//
// public String substring(int start, int end) {
// return text.substring(start, end);
// }
//
// public CharSequence subSequence(int start, int end) {
// return text.subSequence(start, end);
// }
//
// public boolean startsWith(String prefix) {
// return text.startsWith(prefix);
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/MatrixInverseView.java
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.InputType;
import com.gigabytedevelopersinc.app.calculator.MutableString;
import com.gigabytedevelopersinc.app.calculator.R;
package com.gigabytedevelopersinc.app.calculator.view;
public class MatrixInverseView extends AppCompatTextView {
private final static char PLACEHOLDER = '\uFEFF';
public final static String PATTERN = PLACEHOLDER + "^-1";
public MatrixInverseView(Context context) {
super(context);
}
public MatrixInverseView(final AdvancedDisplay display) {
super(display.getContext());
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setText(Html.fromHtml("<sup><small>-1</small></sup>"));
setTextAppearance(display.getContext(), R.style.display_style);
setPadding(0, 0, 0, 0);
}
@Override
public String toString() {
return PATTERN;
}
| public static boolean load(final MutableString text, final AdvancedDisplay parent) { |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/SmallPageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum SmallPanel {
// HEX, ADVANCED, FUNCTION;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gigabytedevelopersinc.app.calculator.Calculator.SmallPanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | package com.gigabytedevelopersinc.app.calculator;
public class SmallPageAdapter extends PagerAdapter {
private View mHexPage;
private View mFunctionPage;
private View mAdvancedPage; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum SmallPanel {
// HEX, ADVANCED, FUNCTION;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/SmallPageAdapter.java
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gigabytedevelopersinc.app.calculator.Calculator.SmallPanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
package com.gigabytedevelopersinc.app.calculator;
public class SmallPageAdapter extends PagerAdapter {
private View mHexPage;
private View mFunctionPage;
private View mAdvancedPage; | private CalculatorViewPager mParent; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/SmallPageAdapter.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum SmallPanel {
// HEX, ADVANCED, FUNCTION;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
| import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gigabytedevelopersinc.app.calculator.Calculator.SmallPanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager; | case BINARY:
mHexPage.findViewById(R.id.bin).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInBinary) {
View v = mHexPage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case DECIMAL:
mHexPage.findViewById(R.id.dec).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mHexPage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case HEXADECIMAL:
mHexPage.findViewById(R.id.hex).setBackgroundResource(R.color.pressed_color);
break;
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/Calculator.java
// public enum SmallPanel {
// HEX, ADVANCED, FUNCTION;
//
// int order;
//
// public void setOrder(int order) {
// this.order = order;
// }
//
// public int getOrder() {
// return order;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/CalculatorViewPager.java
// public class CalculatorViewPager extends ViewPager {
// private boolean enabled;
//
// public CalculatorViewPager(Context context) {
// this(context, null);
// }
//
// public CalculatorViewPager(Context context, AttributeSet attrs) {
// super(context, attrs);
// this.enabled = true;
// }
//
// /**
// * ViewPager inherits ViewGroup's default behavior of delayed clicks on its
// * children, but in order to make the calc buttons more responsive we
// * disable that here.
// */
// public boolean shouldDelayChildPressedState() {
// return false;
// }
//
// @Override
// public boolean onTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onTouchEvent(event);
// }
//
// return false;
// }
//
// @Override
// public boolean onInterceptTouchEvent(MotionEvent event) {
// if(this.enabled) {
// return super.onInterceptTouchEvent(event);
// }
//
// return false;
// }
//
// public void setPagingEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// public boolean getPagingEnabled() {
// return enabled;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/SmallPageAdapter.java
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gigabytedevelopersinc.app.calculator.Calculator.SmallPanel;
import com.gigabytedevelopersinc.app.calculator.view.CalculatorViewPager;
case BINARY:
mHexPage.findViewById(R.id.bin).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInBinary) {
View v = mHexPage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case DECIMAL:
mHexPage.findViewById(R.id.dec).setBackgroundResource(R.color.pressed_color);
for(int i : mLogic.mBaseModule.bannedResourceInDecimal) {
View v = mHexPage.findViewById(i);
if(v != null) v.setEnabled(false);
}
break;
case HEXADECIMAL:
mHexPage.findViewById(R.id.hex).setBackgroundResource(R.color.pressed_color);
break;
}
}
@Override
public int getCount() {
return count;
}
@Override
public void startUpdate(View container) {}
@Override
public Object instantiateItem(View container, int position) { | if(position == SmallPanel.FUNCTION.getOrder() && CalculatorSettings.functionPanel(mParent.getContext())) { |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/MatrixTransposeView.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/MutableString.java
// public class MutableString {
// private String text;
//
// public MutableString() {
//
// }
//
// public MutableString(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public int length() {
// return text.length();
// }
//
// public boolean isEmpty() {
// return text.isEmpty();
// }
//
// public String substring(int start) {
// return text.substring(start);
// }
//
// public String substring(int start, int end) {
// return text.substring(start, end);
// }
//
// public CharSequence subSequence(int start, int end) {
// return text.subSequence(start, end);
// }
//
// public boolean startsWith(String prefix) {
// return text.startsWith(prefix);
// }
// }
| import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.InputType;
import com.gigabytedevelopersinc.app.calculator.MutableString;
import com.gigabytedevelopersinc.app.calculator.R; |
package com.gigabytedevelopersinc.app.calculator.view;
public class MatrixTransposeView extends AppCompatTextView {
public final static String PATTERN = "^T";
public MatrixTransposeView(Context context) {
super(context);
}
public MatrixTransposeView(final AdvancedDisplay display) {
super(display.getContext());
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setText(Html.fromHtml("<sup><small>T</small></sup>"));
setTextAppearance(display.getContext(), R.style.display_style);
setPadding(0, 0, 0, 0);
}
@Override
public String toString() {
return PATTERN;
}
| // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/MutableString.java
// public class MutableString {
// private String text;
//
// public MutableString() {
//
// }
//
// public MutableString(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public int length() {
// return text.length();
// }
//
// public boolean isEmpty() {
// return text.isEmpty();
// }
//
// public String substring(int start) {
// return text.substring(start);
// }
//
// public String substring(int start, int end) {
// return text.substring(start, end);
// }
//
// public CharSequence subSequence(int start, int end) {
// return text.subSequence(start, end);
// }
//
// public boolean startsWith(String prefix) {
// return text.startsWith(prefix);
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/MatrixTransposeView.java
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.InputType;
import com.gigabytedevelopersinc.app.calculator.MutableString;
import com.gigabytedevelopersinc.app.calculator.R;
package com.gigabytedevelopersinc.app.calculator.view;
public class MatrixTransposeView extends AppCompatTextView {
public final static String PATTERN = "^T";
public MatrixTransposeView(Context context) {
super(context);
}
public MatrixTransposeView(final AdvancedDisplay display) {
super(display.getContext());
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setText(Html.fromHtml("<sup><small>T</small></sup>"));
setTextAppearance(display.getContext(), R.style.display_style);
setPadding(0, 0, 0, 0);
}
@Override
public String toString() {
return PATTERN;
}
| public static boolean load(final MutableString text, final AdvancedDisplay parent) { |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/History.java
// public class History {
// private static final int VERSION_1 = 1;
// private static final int MAX_ENTRIES = 100;
// Vector<HistoryEntry> mEntries = new Vector<>();
// private int mPos;
// private BaseAdapter mObserver;
//
// History() {
// clear();
// }
//
// History(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// int size = in.readInt();
// for(int i = 0; i < size; ++i) {
// mEntries.add(new HistoryEntry(version, in));
// }
// mPos = in.readInt();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void setObserver(BaseAdapter observer) {
// mObserver = observer;
// }
//
// private void notifyChanged() {
// if(mObserver != null) {
// mObserver.notifyDataSetChanged();
// }
// }
//
// void clear() {
// mEntries.clear();
// mEntries.add(new HistoryEntry("", ""));
// mPos = 0;
// notifyChanged();
// }
//
// void write(DataOutput out) throws IOException {
// out.writeInt(mEntries.size());
// for(HistoryEntry entry : mEntries) {
// entry.write(out);
// }
// out.writeInt(mPos);
// }
//
// void update(String text) {
// current().setEdited(text);
// }
//
// boolean moveToPrevious() {
// if(mPos > 0) {
// --mPos;
// return true;
// }
// return false;
// }
//
// boolean moveToNext() {
// if(mPos < mEntries.size() - 1) {
// ++mPos;
// return true;
// }
// return false;
// }
//
// void enter(String base, String edited) {
// current().clearEdited();
// if(mEntries.size() >= MAX_ENTRIES) {
// mEntries.remove(0);
// }
// if((mEntries.size() < 2 || !base.equals(mEntries.elementAt(mEntries.size() - 2).getBase())) && !base.isEmpty() && !edited.isEmpty()) {
// mEntries.insertElementAt(new HistoryEntry(base, edited), mEntries.size() - 1);
// }
// mPos = mEntries.size() - 1;
// notifyChanged();
// }
//
// private HistoryEntry current() {
// return mEntries.elementAt(mPos);
// }
//
// String getText() {
// return current().getEdited();
// }
//
// String getBase() {
// return current().getBase();
// }
//
// public void remove(HistoryEntry he) {
// mEntries.remove(he);
// mPos--;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryEntry.java
// public class HistoryEntry {
// private static final int VERSION_1 = 1;
// private String mBase;
// private String mEdited;
//
// HistoryEntry(String base, String edited) {
// mBase = base;
// mEdited = edited;
// }
//
// HistoryEntry(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// mBase = in.readUTF();
// mEdited = in.readUTF();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void write(DataOutput out) throws IOException {
// out.writeUTF(mBase);
// out.writeUTF(mEdited);
// }
//
// @Override
// public String toString() {
// return mBase;
// }
//
// void clearEdited() {
// mEdited = mBase;
// }
//
// public String getEdited() {
// return mEdited;
// }
//
// void setEdited(String edited) {
// mEdited = edited;
// }
//
// public String getBase() {
// return mBase;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.gigabytedevelopersinc.app.calculator.History;
import com.gigabytedevelopersinc.app.calculator.HistoryEntry;
import com.gigabytedevelopersinc.app.calculator.R; | package com.gigabytedevelopersinc.app.calculator.view;
public class HistoryLine extends LinearLayout {
private static final int COPY = 0;
private static final int COPY_BASE = 1;
private static final int COPY_EDITED = 2;
private static final int REMOVE = 3;
private String[] mMenuItemsStrings; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/History.java
// public class History {
// private static final int VERSION_1 = 1;
// private static final int MAX_ENTRIES = 100;
// Vector<HistoryEntry> mEntries = new Vector<>();
// private int mPos;
// private BaseAdapter mObserver;
//
// History() {
// clear();
// }
//
// History(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// int size = in.readInt();
// for(int i = 0; i < size; ++i) {
// mEntries.add(new HistoryEntry(version, in));
// }
// mPos = in.readInt();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void setObserver(BaseAdapter observer) {
// mObserver = observer;
// }
//
// private void notifyChanged() {
// if(mObserver != null) {
// mObserver.notifyDataSetChanged();
// }
// }
//
// void clear() {
// mEntries.clear();
// mEntries.add(new HistoryEntry("", ""));
// mPos = 0;
// notifyChanged();
// }
//
// void write(DataOutput out) throws IOException {
// out.writeInt(mEntries.size());
// for(HistoryEntry entry : mEntries) {
// entry.write(out);
// }
// out.writeInt(mPos);
// }
//
// void update(String text) {
// current().setEdited(text);
// }
//
// boolean moveToPrevious() {
// if(mPos > 0) {
// --mPos;
// return true;
// }
// return false;
// }
//
// boolean moveToNext() {
// if(mPos < mEntries.size() - 1) {
// ++mPos;
// return true;
// }
// return false;
// }
//
// void enter(String base, String edited) {
// current().clearEdited();
// if(mEntries.size() >= MAX_ENTRIES) {
// mEntries.remove(0);
// }
// if((mEntries.size() < 2 || !base.equals(mEntries.elementAt(mEntries.size() - 2).getBase())) && !base.isEmpty() && !edited.isEmpty()) {
// mEntries.insertElementAt(new HistoryEntry(base, edited), mEntries.size() - 1);
// }
// mPos = mEntries.size() - 1;
// notifyChanged();
// }
//
// private HistoryEntry current() {
// return mEntries.elementAt(mPos);
// }
//
// String getText() {
// return current().getEdited();
// }
//
// String getBase() {
// return current().getBase();
// }
//
// public void remove(HistoryEntry he) {
// mEntries.remove(he);
// mPos--;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryEntry.java
// public class HistoryEntry {
// private static final int VERSION_1 = 1;
// private String mBase;
// private String mEdited;
//
// HistoryEntry(String base, String edited) {
// mBase = base;
// mEdited = edited;
// }
//
// HistoryEntry(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// mBase = in.readUTF();
// mEdited = in.readUTF();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void write(DataOutput out) throws IOException {
// out.writeUTF(mBase);
// out.writeUTF(mEdited);
// }
//
// @Override
// public String toString() {
// return mBase;
// }
//
// void clearEdited() {
// mEdited = mBase;
// }
//
// public String getEdited() {
// return mEdited;
// }
//
// void setEdited(String edited) {
// mEdited = edited;
// }
//
// public String getBase() {
// return mBase;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.gigabytedevelopersinc.app.calculator.History;
import com.gigabytedevelopersinc.app.calculator.HistoryEntry;
import com.gigabytedevelopersinc.app.calculator.R;
package com.gigabytedevelopersinc.app.calculator.view;
public class HistoryLine extends LinearLayout {
private static final int COPY = 0;
private static final int COPY_BASE = 1;
private static final int COPY_EDITED = 2;
private static final int REMOVE = 3;
private String[] mMenuItemsStrings; | private HistoryEntry mHistoryEntry; |
gigabytedevelopers/CalcMate | app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/History.java
// public class History {
// private static final int VERSION_1 = 1;
// private static final int MAX_ENTRIES = 100;
// Vector<HistoryEntry> mEntries = new Vector<>();
// private int mPos;
// private BaseAdapter mObserver;
//
// History() {
// clear();
// }
//
// History(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// int size = in.readInt();
// for(int i = 0; i < size; ++i) {
// mEntries.add(new HistoryEntry(version, in));
// }
// mPos = in.readInt();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void setObserver(BaseAdapter observer) {
// mObserver = observer;
// }
//
// private void notifyChanged() {
// if(mObserver != null) {
// mObserver.notifyDataSetChanged();
// }
// }
//
// void clear() {
// mEntries.clear();
// mEntries.add(new HistoryEntry("", ""));
// mPos = 0;
// notifyChanged();
// }
//
// void write(DataOutput out) throws IOException {
// out.writeInt(mEntries.size());
// for(HistoryEntry entry : mEntries) {
// entry.write(out);
// }
// out.writeInt(mPos);
// }
//
// void update(String text) {
// current().setEdited(text);
// }
//
// boolean moveToPrevious() {
// if(mPos > 0) {
// --mPos;
// return true;
// }
// return false;
// }
//
// boolean moveToNext() {
// if(mPos < mEntries.size() - 1) {
// ++mPos;
// return true;
// }
// return false;
// }
//
// void enter(String base, String edited) {
// current().clearEdited();
// if(mEntries.size() >= MAX_ENTRIES) {
// mEntries.remove(0);
// }
// if((mEntries.size() < 2 || !base.equals(mEntries.elementAt(mEntries.size() - 2).getBase())) && !base.isEmpty() && !edited.isEmpty()) {
// mEntries.insertElementAt(new HistoryEntry(base, edited), mEntries.size() - 1);
// }
// mPos = mEntries.size() - 1;
// notifyChanged();
// }
//
// private HistoryEntry current() {
// return mEntries.elementAt(mPos);
// }
//
// String getText() {
// return current().getEdited();
// }
//
// String getBase() {
// return current().getBase();
// }
//
// public void remove(HistoryEntry he) {
// mEntries.remove(he);
// mPos--;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryEntry.java
// public class HistoryEntry {
// private static final int VERSION_1 = 1;
// private String mBase;
// private String mEdited;
//
// HistoryEntry(String base, String edited) {
// mBase = base;
// mEdited = edited;
// }
//
// HistoryEntry(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// mBase = in.readUTF();
// mEdited = in.readUTF();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void write(DataOutput out) throws IOException {
// out.writeUTF(mBase);
// out.writeUTF(mEdited);
// }
//
// @Override
// public String toString() {
// return mBase;
// }
//
// void clearEdited() {
// mEdited = mBase;
// }
//
// public String getEdited() {
// return mEdited;
// }
//
// void setEdited(String edited) {
// mEdited = edited;
// }
//
// public String getBase() {
// return mBase;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.gigabytedevelopersinc.app.calculator.History;
import com.gigabytedevelopersinc.app.calculator.HistoryEntry;
import com.gigabytedevelopersinc.app.calculator.R; | package com.gigabytedevelopersinc.app.calculator.view;
public class HistoryLine extends LinearLayout {
private static final int COPY = 0;
private static final int COPY_BASE = 1;
private static final int COPY_EDITED = 2;
private static final int REMOVE = 3;
private String[] mMenuItemsStrings;
private HistoryEntry mHistoryEntry; | // Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/History.java
// public class History {
// private static final int VERSION_1 = 1;
// private static final int MAX_ENTRIES = 100;
// Vector<HistoryEntry> mEntries = new Vector<>();
// private int mPos;
// private BaseAdapter mObserver;
//
// History() {
// clear();
// }
//
// History(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// int size = in.readInt();
// for(int i = 0; i < size; ++i) {
// mEntries.add(new HistoryEntry(version, in));
// }
// mPos = in.readInt();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void setObserver(BaseAdapter observer) {
// mObserver = observer;
// }
//
// private void notifyChanged() {
// if(mObserver != null) {
// mObserver.notifyDataSetChanged();
// }
// }
//
// void clear() {
// mEntries.clear();
// mEntries.add(new HistoryEntry("", ""));
// mPos = 0;
// notifyChanged();
// }
//
// void write(DataOutput out) throws IOException {
// out.writeInt(mEntries.size());
// for(HistoryEntry entry : mEntries) {
// entry.write(out);
// }
// out.writeInt(mPos);
// }
//
// void update(String text) {
// current().setEdited(text);
// }
//
// boolean moveToPrevious() {
// if(mPos > 0) {
// --mPos;
// return true;
// }
// return false;
// }
//
// boolean moveToNext() {
// if(mPos < mEntries.size() - 1) {
// ++mPos;
// return true;
// }
// return false;
// }
//
// void enter(String base, String edited) {
// current().clearEdited();
// if(mEntries.size() >= MAX_ENTRIES) {
// mEntries.remove(0);
// }
// if((mEntries.size() < 2 || !base.equals(mEntries.elementAt(mEntries.size() - 2).getBase())) && !base.isEmpty() && !edited.isEmpty()) {
// mEntries.insertElementAt(new HistoryEntry(base, edited), mEntries.size() - 1);
// }
// mPos = mEntries.size() - 1;
// notifyChanged();
// }
//
// private HistoryEntry current() {
// return mEntries.elementAt(mPos);
// }
//
// String getText() {
// return current().getEdited();
// }
//
// String getBase() {
// return current().getBase();
// }
//
// public void remove(HistoryEntry he) {
// mEntries.remove(he);
// mPos--;
// }
// }
//
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/HistoryEntry.java
// public class HistoryEntry {
// private static final int VERSION_1 = 1;
// private String mBase;
// private String mEdited;
//
// HistoryEntry(String base, String edited) {
// mBase = base;
// mEdited = edited;
// }
//
// HistoryEntry(int version, DataInput in) throws IOException {
// if(version >= VERSION_1) {
// mBase = in.readUTF();
// mEdited = in.readUTF();
// }
// else {
// throw new IOException("invalid version " + version);
// }
// }
//
// void write(DataOutput out) throws IOException {
// out.writeUTF(mBase);
// out.writeUTF(mEdited);
// }
//
// @Override
// public String toString() {
// return mBase;
// }
//
// void clearEdited() {
// mEdited = mBase;
// }
//
// public String getEdited() {
// return mEdited;
// }
//
// void setEdited(String edited) {
// mEdited = edited;
// }
//
// public String getBase() {
// return mBase;
// }
// }
// Path: app/src/main/java/com/gigabytedevelopersinc/app/calculator/view/HistoryLine.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.gigabytedevelopersinc.app.calculator.History;
import com.gigabytedevelopersinc.app.calculator.HistoryEntry;
import com.gigabytedevelopersinc.app.calculator.R;
package com.gigabytedevelopersinc.app.calculator.view;
public class HistoryLine extends LinearLayout {
private static final int COPY = 0;
private static final int COPY_BASE = 1;
private static final int COPY_EDITED = 2;
private static final int REMOVE = 3;
private String[] mMenuItemsStrings;
private HistoryEntry mHistoryEntry; | private History mHistory; |
apache/commons-fileupload | src/main/java/org/apache/commons/fileupload2/pub/FileUploadIOException.java | // Path: src/main/java/org/apache/commons/fileupload2/FileUploadException.java
// public class FileUploadException extends IOException {
//
// /**
// * Serial version UID, being used, if the exception
// * is serialized.
// */
// private static final long serialVersionUID = 8881893724388807504L;
//
// /**
// * The exceptions cause. We overwrite the cause of
// * the super class, which isn't available in Java 1.3.
// */
// private final Throwable cause;
//
// /**
// * Constructs a new {@code FileUploadException} without message.
// */
// public FileUploadException() {
// this(null, null);
// }
//
// /**
// * Constructs a new {@code FileUploadException} with specified detail
// * message.
// *
// * @param msg the error message.
// */
// public FileUploadException(final String msg) {
// this(msg, null);
// }
//
// /**
// * Creates a new {@code FileUploadException} with the given
// * detail message and cause.
// *
// * @param msg The exceptions detail message.
// * @param cause The exceptions cause.
// */
// public FileUploadException(final String msg, final Throwable cause) {
// super(msg);
// this.cause = cause;
// }
//
// /**
// * Prints this throwable and its backtrace to the specified print stream.
// *
// * @param stream {@code PrintStream} to use for output
// */
// @Override
// public void printStackTrace(final PrintStream stream) {
// super.printStackTrace(stream);
// if (cause != null) {
// stream.println("Caused by:");
// cause.printStackTrace(stream);
// }
// }
//
// /**
// * Prints this throwable and its backtrace to the specified
// * print writer.
// *
// * @param writer {@code PrintWriter} to use for output
// */
// @Override
// public void printStackTrace(final PrintWriter writer) {
// super.printStackTrace(writer);
// if (cause != null) {
// writer.println("Caused by:");
// cause.printStackTrace(writer);
// }
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Throwable getCause() {
// return cause;
// }
//
// }
| import java.io.IOException;
import org.apache.commons.fileupload2.FileUploadException;
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.fileupload2.pub;
/**
* This exception is thrown for hiding an inner
* {@link FileUploadException} in an {@link IOException}.
*/
public class FileUploadIOException extends IOException {
/**
* The exceptions UID, for serializing an instance.
*/
private static final long serialVersionUID = -7047616958165584154L;
/**
* The exceptions cause; we overwrite the parent
* classes field, which is available since Java
* 1.4 only.
*/
| // Path: src/main/java/org/apache/commons/fileupload2/FileUploadException.java
// public class FileUploadException extends IOException {
//
// /**
// * Serial version UID, being used, if the exception
// * is serialized.
// */
// private static final long serialVersionUID = 8881893724388807504L;
//
// /**
// * The exceptions cause. We overwrite the cause of
// * the super class, which isn't available in Java 1.3.
// */
// private final Throwable cause;
//
// /**
// * Constructs a new {@code FileUploadException} without message.
// */
// public FileUploadException() {
// this(null, null);
// }
//
// /**
// * Constructs a new {@code FileUploadException} with specified detail
// * message.
// *
// * @param msg the error message.
// */
// public FileUploadException(final String msg) {
// this(msg, null);
// }
//
// /**
// * Creates a new {@code FileUploadException} with the given
// * detail message and cause.
// *
// * @param msg The exceptions detail message.
// * @param cause The exceptions cause.
// */
// public FileUploadException(final String msg, final Throwable cause) {
// super(msg);
// this.cause = cause;
// }
//
// /**
// * Prints this throwable and its backtrace to the specified print stream.
// *
// * @param stream {@code PrintStream} to use for output
// */
// @Override
// public void printStackTrace(final PrintStream stream) {
// super.printStackTrace(stream);
// if (cause != null) {
// stream.println("Caused by:");
// cause.printStackTrace(stream);
// }
// }
//
// /**
// * Prints this throwable and its backtrace to the specified
// * print writer.
// *
// * @param writer {@code PrintWriter} to use for output
// */
// @Override
// public void printStackTrace(final PrintWriter writer) {
// super.printStackTrace(writer);
// if (cause != null) {
// writer.println("Caused by:");
// cause.printStackTrace(writer);
// }
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Throwable getCause() {
// return cause;
// }
//
// }
// Path: src/main/java/org/apache/commons/fileupload2/pub/FileUploadIOException.java
import java.io.IOException;
import org.apache.commons.fileupload2.FileUploadException;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.fileupload2.pub;
/**
* This exception is thrown for hiding an inner
* {@link FileUploadException} in an {@link IOException}.
*/
public class FileUploadIOException extends IOException {
/**
* The exceptions UID, for serializing an instance.
*/
private static final long serialVersionUID = -7047616958165584154L;
/**
* The exceptions cause; we overwrite the parent
* classes field, which is available since Java
* 1.4 only.
*/
| private final FileUploadException cause;
|
apache/commons-fileupload | src/test/java/org/apache/commons/fileupload2/ProgressListenerTest.java | // Path: src/main/java/org/apache/commons/fileupload2/servlet/ServletFileUpload.java
// public class ServletFileUpload extends FileUpload {
//
// /**
// * Constant for HTTP POST method.
// */
// private static final String POST_METHOD = "POST";
//
// // ---------------------------------------------------------- Class methods
//
// /**
// * Utility method that determines whether the request contains multipart
// * content.
// *
// * @param request The servlet request to be evaluated. Must be non-null.
// *
// * @return {@code true} if the request is multipart;
// * {@code false} otherwise.
// */
// public static final boolean isMultipartContent(
// final HttpServletRequest request) {
// if (!POST_METHOD.equalsIgnoreCase(request.getMethod())) {
// return false;
// }
// return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
// }
//
// // ----------------------------------------------------------- Constructors
//
// /**
// * Constructs an uninitialized instance of this class. A factory must be
// * configured, using {@code setFileItemFactory()}, before attempting
// * to parse requests.
// *
// * @see FileUpload#FileUpload(FileItemFactory)
// */
// public ServletFileUpload() {
// }
//
// /**
// * Constructs an instance of this class which uses the supplied factory to
// * create {@code FileItem} instances.
// *
// * @see FileUpload#FileUpload()
// * @param fileItemFactory The factory to use for creating file items.
// */
// public ServletFileUpload(final FileItemFactory fileItemFactory) {
// super(fileItemFactory);
// }
//
// // --------------------------------------------------------- Public methods
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return A list of {@code FileItem} instances parsed from the
// * request, in the order that they were transmitted.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// */
// public List<FileItem> parseRequest(final HttpServletRequest request)
// throws FileUploadException {
// return parseRequest(new ServletRequestContext(request));
// }
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return A map of {@code FileItem} instances parsed from the request.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// *
// * @since 1.3
// */
// public Map<String, List<FileItem>> parseParameterMap(final HttpServletRequest request)
// throws FileUploadException {
// return parseParameterMap(new ServletRequestContext(request));
// }
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return An iterator to instances of {@code FileItemStream}
// * parsed from the request, in the order that they were
// * transmitted.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// * @throws IOException An I/O error occurred. This may be a network
// * error while communicating with the client or a problem while
// * storing the uploaded content.
// */
// public FileItemIterator getItemIterator(final HttpServletRequest request)
// throws FileUploadException, IOException {
// return super.getItemIterator(new ServletRequestContext(request));
// }
//
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.fileupload2.servlet.ServletFileUpload;
import org.junit.jupiter.api.Test; | */
@Test
public void testProgressListener() throws Exception {
final int NUM_ITEMS = 512;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < NUM_ITEMS; i++) {
final String header = "-----1234\r\n"
+ "Content-Disposition: form-data; name=\"field" + (i + 1) + "\"\r\n"
+ "\r\n";
baos.write(header.getBytes(StandardCharsets.US_ASCII));
for (int j = 0; j < 16384 + i; j++) {
baos.write((byte) j);
}
baos.write("\r\n".getBytes(StandardCharsets.US_ASCII));
}
baos.write("-----1234--\r\n".getBytes(StandardCharsets.US_ASCII));
final byte[] contents = baos.toByteArray();
MockHttpServletRequest request = new MockHttpServletRequest(contents, Constants.CONTENT_TYPE);
runTest(NUM_ITEMS, contents.length, request);
request = new MockHttpServletRequest(contents, Constants.CONTENT_TYPE) {
@Override
public int getContentLength() {
return -1;
}
};
runTest(NUM_ITEMS, contents.length, request);
}
private void runTest(final int NUM_ITEMS, final long pContentLength, final MockHttpServletRequest request) throws FileUploadException, IOException { | // Path: src/main/java/org/apache/commons/fileupload2/servlet/ServletFileUpload.java
// public class ServletFileUpload extends FileUpload {
//
// /**
// * Constant for HTTP POST method.
// */
// private static final String POST_METHOD = "POST";
//
// // ---------------------------------------------------------- Class methods
//
// /**
// * Utility method that determines whether the request contains multipart
// * content.
// *
// * @param request The servlet request to be evaluated. Must be non-null.
// *
// * @return {@code true} if the request is multipart;
// * {@code false} otherwise.
// */
// public static final boolean isMultipartContent(
// final HttpServletRequest request) {
// if (!POST_METHOD.equalsIgnoreCase(request.getMethod())) {
// return false;
// }
// return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
// }
//
// // ----------------------------------------------------------- Constructors
//
// /**
// * Constructs an uninitialized instance of this class. A factory must be
// * configured, using {@code setFileItemFactory()}, before attempting
// * to parse requests.
// *
// * @see FileUpload#FileUpload(FileItemFactory)
// */
// public ServletFileUpload() {
// }
//
// /**
// * Constructs an instance of this class which uses the supplied factory to
// * create {@code FileItem} instances.
// *
// * @see FileUpload#FileUpload()
// * @param fileItemFactory The factory to use for creating file items.
// */
// public ServletFileUpload(final FileItemFactory fileItemFactory) {
// super(fileItemFactory);
// }
//
// // --------------------------------------------------------- Public methods
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return A list of {@code FileItem} instances parsed from the
// * request, in the order that they were transmitted.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// */
// public List<FileItem> parseRequest(final HttpServletRequest request)
// throws FileUploadException {
// return parseRequest(new ServletRequestContext(request));
// }
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return A map of {@code FileItem} instances parsed from the request.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// *
// * @since 1.3
// */
// public Map<String, List<FileItem>> parseParameterMap(final HttpServletRequest request)
// throws FileUploadException {
// return parseParameterMap(new ServletRequestContext(request));
// }
//
// /**
// * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
// * compliant {@code multipart/form-data} stream.
// *
// * @param request The servlet request to be parsed.
// *
// * @return An iterator to instances of {@code FileItemStream}
// * parsed from the request, in the order that they were
// * transmitted.
// *
// * @throws FileUploadException if there are problems reading/parsing
// * the request or storing files.
// * @throws IOException An I/O error occurred. This may be a network
// * error while communicating with the client or a problem while
// * storing the uploaded content.
// */
// public FileItemIterator getItemIterator(final HttpServletRequest request)
// throws FileUploadException, IOException {
// return super.getItemIterator(new ServletRequestContext(request));
// }
//
// }
// Path: src/test/java/org/apache/commons/fileupload2/ProgressListenerTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.fileupload2.servlet.ServletFileUpload;
import org.junit.jupiter.api.Test;
*/
@Test
public void testProgressListener() throws Exception {
final int NUM_ITEMS = 512;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < NUM_ITEMS; i++) {
final String header = "-----1234\r\n"
+ "Content-Disposition: form-data; name=\"field" + (i + 1) + "\"\r\n"
+ "\r\n";
baos.write(header.getBytes(StandardCharsets.US_ASCII));
for (int j = 0; j < 16384 + i; j++) {
baos.write((byte) j);
}
baos.write("\r\n".getBytes(StandardCharsets.US_ASCII));
}
baos.write("-----1234--\r\n".getBytes(StandardCharsets.US_ASCII));
final byte[] contents = baos.toByteArray();
MockHttpServletRequest request = new MockHttpServletRequest(contents, Constants.CONTENT_TYPE);
runTest(NUM_ITEMS, contents.length, request);
request = new MockHttpServletRequest(contents, Constants.CONTENT_TYPE) {
@Override
public int getContentLength() {
return -1;
}
};
runTest(NUM_ITEMS, contents.length, request);
}
private void runTest(final int NUM_ITEMS, final long pContentLength, final MockHttpServletRequest request) throws FileUploadException, IOException { | final ServletFileUpload upload = new ServletFileUpload(); |
apache/commons-fileupload | src/main/java/org/apache/commons/fileupload2/util/Streams.java | // Path: src/main/java/org/apache/commons/fileupload2/InvalidFileNameException.java
// public class InvalidFileNameException extends RuntimeException {
//
// /**
// * Serial version UID, being used, if the exception
// * is serialized.
// */
// private static final long serialVersionUID = 7922042602454350470L;
//
// /**
// * The file name causing the exception.
// */
// private final String name;
//
// /**
// * Creates a new instance.
// *
// * @param pName The file name causing the exception.
// * @param pMessage A human readable error message.
// */
// public InvalidFileNameException(final String pName, final String pMessage) {
// super(pMessage);
// name = pName;
// }
//
// /**
// * Returns the invalid file name.
// *
// * @return the invalid file name.
// */
// public String getName() {
// return name;
// }
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.fileupload2.InvalidFileNameException; | final ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(inputStream, baos, true);
return baos.toString(encoding);
}
/**
* Checks, whether the given file name is valid in the sense,
* that it doesn't contain any NUL characters. If the file name
* is valid, it will be returned without any modifications. Otherwise,
* an {@link InvalidFileNameException} is raised.
*
* @param fileName The file name to check
* @return Unmodified file name, if valid.
* @throws InvalidFileNameException The file name was found to be invalid.
*/
public static String checkFileName(final String fileName) {
if (fileName != null && fileName.indexOf('\u0000') != -1) {
// pFileName.replace("\u0000", "\\0")
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < fileName.length(); i++) {
final char c = fileName.charAt(i);
switch (c) {
case 0:
sb.append("\\0");
break;
default:
sb.append(c);
break;
}
} | // Path: src/main/java/org/apache/commons/fileupload2/InvalidFileNameException.java
// public class InvalidFileNameException extends RuntimeException {
//
// /**
// * Serial version UID, being used, if the exception
// * is serialized.
// */
// private static final long serialVersionUID = 7922042602454350470L;
//
// /**
// * The file name causing the exception.
// */
// private final String name;
//
// /**
// * Creates a new instance.
// *
// * @param pName The file name causing the exception.
// * @param pMessage A human readable error message.
// */
// public InvalidFileNameException(final String pName, final String pMessage) {
// super(pMessage);
// name = pName;
// }
//
// /**
// * Returns the invalid file name.
// *
// * @return the invalid file name.
// */
// public String getName() {
// return name;
// }
//
// }
// Path: src/main/java/org/apache/commons/fileupload2/util/Streams.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.fileupload2.InvalidFileNameException;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(inputStream, baos, true);
return baos.toString(encoding);
}
/**
* Checks, whether the given file name is valid in the sense,
* that it doesn't contain any NUL characters. If the file name
* is valid, it will be returned without any modifications. Otherwise,
* an {@link InvalidFileNameException} is raised.
*
* @param fileName The file name to check
* @return Unmodified file name, if valid.
* @throws InvalidFileNameException The file name was found to be invalid.
*/
public static String checkFileName(final String fileName) {
if (fileName != null && fileName.indexOf('\u0000') != -1) {
// pFileName.replace("\u0000", "\\0")
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < fileName.length(); i++) {
final char c = fileName.charAt(i);
switch (c) {
case 0:
sb.append("\\0");
break;
default:
sb.append(c);
break;
}
} | throw new InvalidFileNameException(fileName, |
apache/commons-fileupload | src/test/java/org/apache/commons/fileupload2/FileItemHeadersTest.java | // Path: src/main/java/org/apache/commons/fileupload2/util/FileItemHeadersImpl.java
// public class FileItemHeadersImpl implements FileItemHeaders, Serializable {
//
// /**
// * Serial version UID, being used, if serialized.
// */
// private static final long serialVersionUID = -4455695752627032559L;
//
// /**
// * Map of {@code String} keys to a {@code List} of
// * {@code String} instances.
// */
// private final Map<String, List<String>> headerNameToValueListMap = new LinkedHashMap<>();
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getHeader(final String name) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// final List<String> headerValueList = headerNameToValueListMap.get(nameLower);
// if (null == headerValueList) {
// return null;
// }
// return headerValueList.get(0);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Iterator<String> getHeaderNames() {
// return headerNameToValueListMap.keySet().iterator();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Iterator<String> getHeaders(final String name) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// List<String> headerValueList = headerNameToValueListMap.get(nameLower);
// if (null == headerValueList) {
// headerValueList = Collections.emptyList();
// }
// return headerValueList.iterator();
// }
//
// /**
// * Method to add header values to this instance.
// *
// * @param name name of this header
// * @param value value of this header
// */
// public synchronized void addHeader(final String name, final String value) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// final List<String> headerValueList = headerNameToValueListMap.
// computeIfAbsent(nameLower, k -> new ArrayList<>());
// headerValueList.add(value);
// }
//
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import org.apache.commons.fileupload2.util.FileItemHeadersImpl;
import org.junit.jupiter.api.Test; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.fileupload2;
/**
* Unit tests {@link FileItemHeaders} and
* {@link FileItemHeadersImpl}.
*/
public class FileItemHeadersTest {
/**
* @throws Exception
*/
@Test
public void testFileItemHeaders() throws Exception { | // Path: src/main/java/org/apache/commons/fileupload2/util/FileItemHeadersImpl.java
// public class FileItemHeadersImpl implements FileItemHeaders, Serializable {
//
// /**
// * Serial version UID, being used, if serialized.
// */
// private static final long serialVersionUID = -4455695752627032559L;
//
// /**
// * Map of {@code String} keys to a {@code List} of
// * {@code String} instances.
// */
// private final Map<String, List<String>> headerNameToValueListMap = new LinkedHashMap<>();
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getHeader(final String name) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// final List<String> headerValueList = headerNameToValueListMap.get(nameLower);
// if (null == headerValueList) {
// return null;
// }
// return headerValueList.get(0);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Iterator<String> getHeaderNames() {
// return headerNameToValueListMap.keySet().iterator();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Iterator<String> getHeaders(final String name) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// List<String> headerValueList = headerNameToValueListMap.get(nameLower);
// if (null == headerValueList) {
// headerValueList = Collections.emptyList();
// }
// return headerValueList.iterator();
// }
//
// /**
// * Method to add header values to this instance.
// *
// * @param name name of this header
// * @param value value of this header
// */
// public synchronized void addHeader(final String name, final String value) {
// final String nameLower = name.toLowerCase(Locale.ENGLISH);
// final List<String> headerValueList = headerNameToValueListMap.
// computeIfAbsent(nameLower, k -> new ArrayList<>());
// headerValueList.add(value);
// }
//
// }
// Path: src/test/java/org/apache/commons/fileupload2/FileItemHeadersTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import org.apache.commons.fileupload2.util.FileItemHeadersImpl;
import org.junit.jupiter.api.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.fileupload2;
/**
* Unit tests {@link FileItemHeaders} and
* {@link FileItemHeadersImpl}.
*/
public class FileItemHeadersTest {
/**
* @throws Exception
*/
@Test
public void testFileItemHeaders() throws Exception { | final FileItemHeadersImpl aMutableFileItemHeaders = new FileItemHeadersImpl(); |
AmailP/robot-plugin | src/main/java/amailp/intellij/robot/extensions/ParserDefinition.java | // Path: src/main/java/amailp/intellij/robot/elements/RobotTokenTypes.java
// public interface RobotTokenTypes {
//
//
// final IElementType BadCharacter = TokenType.BAD_CHARACTER;
//
// final IElementType LineTerminator = new RobotIElementType("LineTerminator");
//
// final IElementType SettingsHeader = new RobotIElementType("SettingsHeader");
// final IElementType TestCasesHeader = new RobotIElementType("TestCasesHeader");
// final IElementType KeywordsHeader = new RobotIElementType("KeywordsHeader");
// final IElementType VariablesHeader = new RobotIElementType("VariablesHeader");
// final IElementType TasksHeader = new RobotIElementType("TasksHeader");
//
// final IElementType Ellipsis = new RobotIElementType("Ellipsis");
// final IElementType ScalarVariable = new RobotIElementType("ScalarVariable");
// final IElementType ListVariable = new RobotIElementType("ListVariable");
// final IElementType DictionaryVariable = new RobotIElementType("DictionaryVariable");
// final IElementType EnvironmentVariable = new RobotIElementType("EnvironmentVariable");
// final IElementType TestCaseSetting = new RobotIElementType("TestCaseSetting");
// final IElementType Word = new RobotIElementType("Word");
// final IElementType Space = new RobotIElementType("Space");
// final IElementType Separator = new RobotIElementType("Separator");
// final IElementType IrrelevantSpaces = new RobotIElementType("IrrelevantSpaces");
// final IElementType BlankLine = new RobotIElementType("BlankLine");
// final IElementType Comment = new RobotIElementType("Comment");
// final IElementType WithName = new RobotIElementType("LibraryAliasSeparator");
//
// final TokenSet WhitespacesTokens = TokenSet.create(IrrelevantSpaces, BlankLine);
// final TokenSet CommentsTokens = TokenSet.create(Comment);
// final TokenSet StringLiteralElements = TokenSet.EMPTY;
// final TokenSet HeaderTokens = TokenSet.create(SettingsHeader, TestCasesHeader, KeywordsHeader, VariablesHeader, TasksHeader);
// }
| import amailp.intellij.robot.elements.RobotTokenTypes;
import amailp.intellij.robot.lang.RobotLanguage;
import amailp.intellij.robot.lexer.RobotLexer;
import amailp.intellij.robot.parser.PsiElementBuilder;
import amailp.intellij.robot.parser.RobotParser$;
import amailp.intellij.robot.psi.RobotPsiFile;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull; | package amailp.intellij.robot.extensions;
public class ParserDefinition implements com.intellij.lang.ParserDefinition {
@Override
@NotNull
public Lexer createLexer(Project project) {
return new RobotLexer();
}
@Override
@NotNull
public TokenSet getWhitespaceTokens() { | // Path: src/main/java/amailp/intellij/robot/elements/RobotTokenTypes.java
// public interface RobotTokenTypes {
//
//
// final IElementType BadCharacter = TokenType.BAD_CHARACTER;
//
// final IElementType LineTerminator = new RobotIElementType("LineTerminator");
//
// final IElementType SettingsHeader = new RobotIElementType("SettingsHeader");
// final IElementType TestCasesHeader = new RobotIElementType("TestCasesHeader");
// final IElementType KeywordsHeader = new RobotIElementType("KeywordsHeader");
// final IElementType VariablesHeader = new RobotIElementType("VariablesHeader");
// final IElementType TasksHeader = new RobotIElementType("TasksHeader");
//
// final IElementType Ellipsis = new RobotIElementType("Ellipsis");
// final IElementType ScalarVariable = new RobotIElementType("ScalarVariable");
// final IElementType ListVariable = new RobotIElementType("ListVariable");
// final IElementType DictionaryVariable = new RobotIElementType("DictionaryVariable");
// final IElementType EnvironmentVariable = new RobotIElementType("EnvironmentVariable");
// final IElementType TestCaseSetting = new RobotIElementType("TestCaseSetting");
// final IElementType Word = new RobotIElementType("Word");
// final IElementType Space = new RobotIElementType("Space");
// final IElementType Separator = new RobotIElementType("Separator");
// final IElementType IrrelevantSpaces = new RobotIElementType("IrrelevantSpaces");
// final IElementType BlankLine = new RobotIElementType("BlankLine");
// final IElementType Comment = new RobotIElementType("Comment");
// final IElementType WithName = new RobotIElementType("LibraryAliasSeparator");
//
// final TokenSet WhitespacesTokens = TokenSet.create(IrrelevantSpaces, BlankLine);
// final TokenSet CommentsTokens = TokenSet.create(Comment);
// final TokenSet StringLiteralElements = TokenSet.EMPTY;
// final TokenSet HeaderTokens = TokenSet.create(SettingsHeader, TestCasesHeader, KeywordsHeader, VariablesHeader, TasksHeader);
// }
// Path: src/main/java/amailp/intellij/robot/extensions/ParserDefinition.java
import amailp.intellij.robot.elements.RobotTokenTypes;
import amailp.intellij.robot.lang.RobotLanguage;
import amailp.intellij.robot.lexer.RobotLexer;
import amailp.intellij.robot.parser.PsiElementBuilder;
import amailp.intellij.robot.parser.RobotParser$;
import amailp.intellij.robot.psi.RobotPsiFile;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;
package amailp.intellij.robot.extensions;
public class ParserDefinition implements com.intellij.lang.ParserDefinition {
@Override
@NotNull
public Lexer createLexer(Project project) {
return new RobotLexer();
}
@Override
@NotNull
public TokenSet getWhitespaceTokens() { | return RobotTokenTypes.WhitespacesTokens; |
lanixzcj/LoveTalkClient | src/com/example/lovetalk/view/EnLetterView.java | // Path: src/com/example/lovetalk/util/PixelUtil.java
// public class PixelUtil {
// private static Resources resources = Resources.getSystem();
// private static int desityDpi = resources.getDisplayMetrics().densityDpi;
// private static float scaledDensity = resources.getDisplayMetrics().scaledDensity;
//
// public static int dp2px(float value) {
// final float scale = desityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// public static int px2dp(float value) {
// final float scale = desityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// public static int sp2px(float value) {
// float spvalue = value * scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// public static int px2sp(float value) {
// final float scale = scaledDensity;
// return (int) (value / scale + 0.5f);
// }
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.example.lovetalk.R;
import com.example.lovetalk.util.PixelUtil; |
private TextView textDialog;
public void setTextView(TextView mTextDialog) {
this.textDialog = mTextDialog;
}
public EnLetterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EnLetterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EnLetterView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
int singleHeight = height / letters.length;
for (int i = 0; i < letters.length; i++) {
paint.setColor(getResources().getColor(
R.color.color_bottom_text_normal));
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setAntiAlias(true); | // Path: src/com/example/lovetalk/util/PixelUtil.java
// public class PixelUtil {
// private static Resources resources = Resources.getSystem();
// private static int desityDpi = resources.getDisplayMetrics().densityDpi;
// private static float scaledDensity = resources.getDisplayMetrics().scaledDensity;
//
// public static int dp2px(float value) {
// final float scale = desityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// public static int px2dp(float value) {
// final float scale = desityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// public static int sp2px(float value) {
// float spvalue = value * scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// public static int px2sp(float value) {
// final float scale = scaledDensity;
// return (int) (value / scale + 0.5f);
// }
// }
// Path: src/com/example/lovetalk/view/EnLetterView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.example.lovetalk.R;
import com.example.lovetalk.util.PixelUtil;
private TextView textDialog;
public void setTextView(TextView mTextDialog) {
this.textDialog = mTextDialog;
}
public EnLetterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EnLetterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EnLetterView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
int singleHeight = height / letters.length;
for (int i = 0; i < letters.length; i++) {
paint.setColor(getResources().getColor(
R.color.color_bottom_text_normal));
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setAntiAlias(true); | paint.setTextSize(PixelUtil.sp2px(12)); |
lanixzcj/LoveTalkClient | src/com/example/lovetalk/view/EmotionEditText.java | // Path: src/com/example/lovetalk/util/EmotionUtils.java
// public class EmotionUtils {
// public static List<String> emotionTexts;
// public static List<String> emotionTexts1;
// public static List<String> emotionTexts2;
//
// private static List<String> emotions;
// public static int[] emotionCodes = new int[]{0x1F601, 0x1F602, 0x1F603, 0x1F604, 0x1F605, 0x1F606, 0x1F609, 0x1F60A, 0x1F60B, 0x1F60C,
// 0x1F60D, 0x1F60F, 0x1F612, 0x1F613, 0x1F614, 0x1F616, 0x1F618, 0x1F61A, 0x1F61C, 0x1F61D, 0x1F61E, 0x1F620, 0x1F621, 0x1F622, 0x1F623, 0x1F624,
// 0x1F625, 0x1F628, 0x1F629, 0x1F62A, 0x1F62B, 0x1F62D, 0x1F630, 0x1F631, 0x1F632, 0x1F633, 0x1F635, 0x1F637};
// public static List<String> emotions1, emotions2;
// public static String[] emojiCodes = new String[]{"\\u1f60a", "\\u1f60c",
// "\\u1f60d", "\\u1f60f", "\\u1f61a", "\\u1f61b", "\\u1f61c", "\\u1f61e", "\\u1f62a", "\\u1f601", "\\u1f602", "\\u1f603",
// "\\u1f604", "\\u1f609", "\\u1f612", "\\u1f613", "\\u1f614", "\\u1f616", "\\u1f618", "\\u1f620", "\\u1f621", "\\u1f622",
// "\\u1f621", "\\u1f622", "\\u1f623", "\\u1f625", "\\u1f628", "\\u1f630", "\\u1f631", "\\u1f632", "\\u1f633", "\\u1f637",
// "\\u1f44d", "\\u1f44e", "\\u1f44f"};
//
// static String getEmojiByUnicode(int unicode) {
// return new String(Character.toChars(unicode));
// }
//
// private static Pattern pattern;
//
// static {
// emotions = new ArrayList<String>();
// int i;
// for (i = 0; i < emotionCodes.length; i++) {
// emotions.add(getEmojiByUnicode(emotionCodes[i]));
// }
// emotions1 = emotions.subList(0, 21);
// emotions2 = emotions.subList(21, emotions.size());
//
// emotionTexts = new ArrayList<String>();
// for (String emojiCode : emojiCodes) {
// emotionTexts.add(emojiCode);
// }
// emotionTexts1 = emotionTexts.subList(0, 21);
// emotionTexts2 = emotionTexts.subList(21, emotionTexts.size());
// pattern = buildPattern();
// }
//
// private static Pattern buildPattern() {
// return Pattern.compile("\\\\u1f[a-z0-9]{3}");
// }
//
// public static boolean haveEmotion(String text) {
// Matcher matcher = pattern.matcher(text);
// if (matcher.find()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static CharSequence scaleEmotions(String text) {
// SpannableString spannableString = new SpannableString(text);
// for (String emotion : emotions) {
// Pattern pattern = Pattern.compile(emotion);
// Matcher matcher = pattern.matcher(text);
// while (matcher.find()) {
// int start = matcher.start();
// int end = matcher.end();
// spannableString.setSpan(new RelativeSizeSpan(1.2f), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
// }
// }
// return spannableString;
// }
//
// public static CharSequence replace(Context ctx, String text) {
// SpannableString spannableString = new SpannableString(text);
// Matcher matcher = pattern.matcher(text);
// while (matcher.find()) {
// String factText = matcher.group();
// String key = factText.substring(1);
// if (emotionTexts.contains(factText)) {
// Bitmap bitmap = getDrawableByName(ctx, key);
// ImageSpan image = new ImageSpan(ctx, bitmap);
// int start = matcher.start();
// int end = matcher.end();
// spannableString.setSpan(image, start, end,
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// }
// return spannableString;
// }
//
// public static Bitmap getDrawableByName(Context ctx, String name) {
// BitmapFactory.Options options = new BitmapFactory.Options();
// Bitmap bitmap = BitmapFactory.decodeResource(ctx.getResources(),
// ctx.getResources().getIdentifier(name, "drawable",
// ctx.getPackageName()), options);
// return bitmap;
// }
// }
| import com.example.lovetalk.util.EmotionUtils;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.EditText; | package com.example.lovetalk.view;
public class EmotionEditText extends EditText {
public EmotionEditText(Context context) {
super(context);
}
public EmotionEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EmotionEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setText(CharSequence text, BufferType type) {
if (!TextUtils.isEmpty(text)) { | // Path: src/com/example/lovetalk/util/EmotionUtils.java
// public class EmotionUtils {
// public static List<String> emotionTexts;
// public static List<String> emotionTexts1;
// public static List<String> emotionTexts2;
//
// private static List<String> emotions;
// public static int[] emotionCodes = new int[]{0x1F601, 0x1F602, 0x1F603, 0x1F604, 0x1F605, 0x1F606, 0x1F609, 0x1F60A, 0x1F60B, 0x1F60C,
// 0x1F60D, 0x1F60F, 0x1F612, 0x1F613, 0x1F614, 0x1F616, 0x1F618, 0x1F61A, 0x1F61C, 0x1F61D, 0x1F61E, 0x1F620, 0x1F621, 0x1F622, 0x1F623, 0x1F624,
// 0x1F625, 0x1F628, 0x1F629, 0x1F62A, 0x1F62B, 0x1F62D, 0x1F630, 0x1F631, 0x1F632, 0x1F633, 0x1F635, 0x1F637};
// public static List<String> emotions1, emotions2;
// public static String[] emojiCodes = new String[]{"\\u1f60a", "\\u1f60c",
// "\\u1f60d", "\\u1f60f", "\\u1f61a", "\\u1f61b", "\\u1f61c", "\\u1f61e", "\\u1f62a", "\\u1f601", "\\u1f602", "\\u1f603",
// "\\u1f604", "\\u1f609", "\\u1f612", "\\u1f613", "\\u1f614", "\\u1f616", "\\u1f618", "\\u1f620", "\\u1f621", "\\u1f622",
// "\\u1f621", "\\u1f622", "\\u1f623", "\\u1f625", "\\u1f628", "\\u1f630", "\\u1f631", "\\u1f632", "\\u1f633", "\\u1f637",
// "\\u1f44d", "\\u1f44e", "\\u1f44f"};
//
// static String getEmojiByUnicode(int unicode) {
// return new String(Character.toChars(unicode));
// }
//
// private static Pattern pattern;
//
// static {
// emotions = new ArrayList<String>();
// int i;
// for (i = 0; i < emotionCodes.length; i++) {
// emotions.add(getEmojiByUnicode(emotionCodes[i]));
// }
// emotions1 = emotions.subList(0, 21);
// emotions2 = emotions.subList(21, emotions.size());
//
// emotionTexts = new ArrayList<String>();
// for (String emojiCode : emojiCodes) {
// emotionTexts.add(emojiCode);
// }
// emotionTexts1 = emotionTexts.subList(0, 21);
// emotionTexts2 = emotionTexts.subList(21, emotionTexts.size());
// pattern = buildPattern();
// }
//
// private static Pattern buildPattern() {
// return Pattern.compile("\\\\u1f[a-z0-9]{3}");
// }
//
// public static boolean haveEmotion(String text) {
// Matcher matcher = pattern.matcher(text);
// if (matcher.find()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static CharSequence scaleEmotions(String text) {
// SpannableString spannableString = new SpannableString(text);
// for (String emotion : emotions) {
// Pattern pattern = Pattern.compile(emotion);
// Matcher matcher = pattern.matcher(text);
// while (matcher.find()) {
// int start = matcher.start();
// int end = matcher.end();
// spannableString.setSpan(new RelativeSizeSpan(1.2f), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
// }
// }
// return spannableString;
// }
//
// public static CharSequence replace(Context ctx, String text) {
// SpannableString spannableString = new SpannableString(text);
// Matcher matcher = pattern.matcher(text);
// while (matcher.find()) {
// String factText = matcher.group();
// String key = factText.substring(1);
// if (emotionTexts.contains(factText)) {
// Bitmap bitmap = getDrawableByName(ctx, key);
// ImageSpan image = new ImageSpan(ctx, bitmap);
// int start = matcher.start();
// int end = matcher.end();
// spannableString.setSpan(image, start, end,
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// }
// return spannableString;
// }
//
// public static Bitmap getDrawableByName(Context ctx, String name) {
// BitmapFactory.Options options = new BitmapFactory.Options();
// Bitmap bitmap = BitmapFactory.decodeResource(ctx.getResources(),
// ctx.getResources().getIdentifier(name, "drawable",
// ctx.getPackageName()), options);
// return bitmap;
// }
// }
// Path: src/com/example/lovetalk/view/EmotionEditText.java
import com.example.lovetalk.util.EmotionUtils;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.EditText;
package com.example.lovetalk.view;
public class EmotionEditText extends EditText {
public EmotionEditText(Context context) {
super(context);
}
public EmotionEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EmotionEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setText(CharSequence text, BufferType type) {
if (!TextUtils.isEmpty(text)) { | super.setText(EmotionUtils.replace(getContext(), text.toString()), type); |
lanixzcj/LoveTalkClient | src/com/example/lovetalk/adapter/AddFriendAdapter.java | // Path: src/com/example/lovetalk/service/AddRequestService.java
// public class AddRequestService {
// public static int countAddRequests() throws AVException {
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// q.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());
// try {
// return q.count();
// } catch (AVException e) {
// if (e.getCode() == AVException.CACHE_MISS) {
// return 0;
// } else {
// throw e;
// }
// }
// }
//
// public static List<AddRequest> findAddRequests() throws AVException {
// AVUser user = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.include(AddRequest.FROM_USER);
// q.whereEqualTo(AddRequest.TO_USER, user);
// q.orderByDescending("createdAt");
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// return q.find();
// }
//
// public static boolean hasAddRequest() throws AVException {
// PreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(DemoApplication.context);
// int addRequestN = preferenceMap.getAddRequestN();
// int requestN = countAddRequests();
// if (requestN > addRequestN) {
// return true;
// } else {
// return false;
// }
// }
//
// public static void agreeAddRequest(final AddRequest addRequest, final SaveCallback saveCallback) {
// UserService.addFriend(addRequest.getFromUser().getObjectId(), new SaveCallback() {
// @Override
// public void done(AVException e) {
// if (e != null) {
// if (e.getCode() == AVException.DUPLICATE_VALUE) {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// } else {
// saveCallback.done(e);
// }
// } else {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// }
// }
// });
// }
//
// public static void createAddRequest(AVUser toUser) throws Exception {
// AVUser curUser = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.whereEqualTo(AddRequest.FROM_USER, curUser);
// q.whereEqualTo(AddRequest.TO_USER, toUser);
// q.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);
// int count = 0;
// try {
// count = q.count();
// } catch (AVException e) {
// e.printStackTrace();
// if (e.getCode() == AVException.OBJECT_NOT_FOUND) {
// count = 0;
// } else {
// throw e;
// }
// }
// if (count > 0) {
// throw new Exception(DemoApplication.context.getString(R.string.contact_alreadyCreateAddRequest));
// } else {
// AddRequest add = new AddRequest();
// add.setFromUser(curUser);
// add.setToUser(toUser);
// add.setStatus(AddRequest.STATUS_WAIT);
// add.save();
// }
// }
//
// public static void createAddRequestInBackground(Context ctx, final AVUser user) {
// new MyAsyncTask(ctx) {
// @Override
// protected void doInBack() throws Exception {
// AddRequestService.createAddRequest(user);
// }
//
// @Override
// protected void onSucceed() {
// Utils.toast(R.string.contact_sendRequestSucceed);
// }
// }.execute();
// }
// }
//
// Path: src/com/example/lovetalk/view/ViewHolder.java
// public class ViewHolder {
// public static <T extends View> T findViewById(View view, int id) {
// SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
// if (viewHolder == null) {
// viewHolder = new SparseArray<View>();
// view.setTag(viewHolder);
// }
// View childView = viewHolder.get(id);
// if (childView == null) {
// childView = view.findViewById(id);
// viewHolder.put(id, childView);
// }
// return (T) childView;
// }
// }
| import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.R;
import com.example.lovetalk.service.AddRequestService;
import com.example.lovetalk.view.ViewHolder;
import java.util.List; | package com.example.lovetalk.adapter;
public class AddFriendAdapter extends BaseListAdapter<AVUser> {
Context mContext;
public AddFriendAdapter(Context context, List<AVUser> list) {
super(context, list);
// TODO Auto-generated constructor stub
mContext = context;
}
@Override
public View getView(int position, View conView, ViewGroup parent) {
// TODO Auto-generated method stub
if (conView == null) {
conView = inflater.inflate(R.layout.contact_add_friend_item, null);
}
final AVUser user = datas.get(position); | // Path: src/com/example/lovetalk/service/AddRequestService.java
// public class AddRequestService {
// public static int countAddRequests() throws AVException {
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// q.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());
// try {
// return q.count();
// } catch (AVException e) {
// if (e.getCode() == AVException.CACHE_MISS) {
// return 0;
// } else {
// throw e;
// }
// }
// }
//
// public static List<AddRequest> findAddRequests() throws AVException {
// AVUser user = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.include(AddRequest.FROM_USER);
// q.whereEqualTo(AddRequest.TO_USER, user);
// q.orderByDescending("createdAt");
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// return q.find();
// }
//
// public static boolean hasAddRequest() throws AVException {
// PreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(DemoApplication.context);
// int addRequestN = preferenceMap.getAddRequestN();
// int requestN = countAddRequests();
// if (requestN > addRequestN) {
// return true;
// } else {
// return false;
// }
// }
//
// public static void agreeAddRequest(final AddRequest addRequest, final SaveCallback saveCallback) {
// UserService.addFriend(addRequest.getFromUser().getObjectId(), new SaveCallback() {
// @Override
// public void done(AVException e) {
// if (e != null) {
// if (e.getCode() == AVException.DUPLICATE_VALUE) {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// } else {
// saveCallback.done(e);
// }
// } else {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// }
// }
// });
// }
//
// public static void createAddRequest(AVUser toUser) throws Exception {
// AVUser curUser = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.whereEqualTo(AddRequest.FROM_USER, curUser);
// q.whereEqualTo(AddRequest.TO_USER, toUser);
// q.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);
// int count = 0;
// try {
// count = q.count();
// } catch (AVException e) {
// e.printStackTrace();
// if (e.getCode() == AVException.OBJECT_NOT_FOUND) {
// count = 0;
// } else {
// throw e;
// }
// }
// if (count > 0) {
// throw new Exception(DemoApplication.context.getString(R.string.contact_alreadyCreateAddRequest));
// } else {
// AddRequest add = new AddRequest();
// add.setFromUser(curUser);
// add.setToUser(toUser);
// add.setStatus(AddRequest.STATUS_WAIT);
// add.save();
// }
// }
//
// public static void createAddRequestInBackground(Context ctx, final AVUser user) {
// new MyAsyncTask(ctx) {
// @Override
// protected void doInBack() throws Exception {
// AddRequestService.createAddRequest(user);
// }
//
// @Override
// protected void onSucceed() {
// Utils.toast(R.string.contact_sendRequestSucceed);
// }
// }.execute();
// }
// }
//
// Path: src/com/example/lovetalk/view/ViewHolder.java
// public class ViewHolder {
// public static <T extends View> T findViewById(View view, int id) {
// SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
// if (viewHolder == null) {
// viewHolder = new SparseArray<View>();
// view.setTag(viewHolder);
// }
// View childView = viewHolder.get(id);
// if (childView == null) {
// childView = view.findViewById(id);
// viewHolder.put(id, childView);
// }
// return (T) childView;
// }
// }
// Path: src/com/example/lovetalk/adapter/AddFriendAdapter.java
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.R;
import com.example.lovetalk.service.AddRequestService;
import com.example.lovetalk.view.ViewHolder;
import java.util.List;
package com.example.lovetalk.adapter;
public class AddFriendAdapter extends BaseListAdapter<AVUser> {
Context mContext;
public AddFriendAdapter(Context context, List<AVUser> list) {
super(context, list);
// TODO Auto-generated constructor stub
mContext = context;
}
@Override
public View getView(int position, View conView, ViewGroup parent) {
// TODO Auto-generated method stub
if (conView == null) {
conView = inflater.inflate(R.layout.contact_add_friend_item, null);
}
final AVUser user = datas.get(position); | TextView nameView = ViewHolder.findViewById(conView, R.id.name); |
lanixzcj/LoveTalkClient | src/com/example/lovetalk/adapter/AddFriendAdapter.java | // Path: src/com/example/lovetalk/service/AddRequestService.java
// public class AddRequestService {
// public static int countAddRequests() throws AVException {
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// q.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());
// try {
// return q.count();
// } catch (AVException e) {
// if (e.getCode() == AVException.CACHE_MISS) {
// return 0;
// } else {
// throw e;
// }
// }
// }
//
// public static List<AddRequest> findAddRequests() throws AVException {
// AVUser user = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.include(AddRequest.FROM_USER);
// q.whereEqualTo(AddRequest.TO_USER, user);
// q.orderByDescending("createdAt");
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// return q.find();
// }
//
// public static boolean hasAddRequest() throws AVException {
// PreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(DemoApplication.context);
// int addRequestN = preferenceMap.getAddRequestN();
// int requestN = countAddRequests();
// if (requestN > addRequestN) {
// return true;
// } else {
// return false;
// }
// }
//
// public static void agreeAddRequest(final AddRequest addRequest, final SaveCallback saveCallback) {
// UserService.addFriend(addRequest.getFromUser().getObjectId(), new SaveCallback() {
// @Override
// public void done(AVException e) {
// if (e != null) {
// if (e.getCode() == AVException.DUPLICATE_VALUE) {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// } else {
// saveCallback.done(e);
// }
// } else {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// }
// }
// });
// }
//
// public static void createAddRequest(AVUser toUser) throws Exception {
// AVUser curUser = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.whereEqualTo(AddRequest.FROM_USER, curUser);
// q.whereEqualTo(AddRequest.TO_USER, toUser);
// q.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);
// int count = 0;
// try {
// count = q.count();
// } catch (AVException e) {
// e.printStackTrace();
// if (e.getCode() == AVException.OBJECT_NOT_FOUND) {
// count = 0;
// } else {
// throw e;
// }
// }
// if (count > 0) {
// throw new Exception(DemoApplication.context.getString(R.string.contact_alreadyCreateAddRequest));
// } else {
// AddRequest add = new AddRequest();
// add.setFromUser(curUser);
// add.setToUser(toUser);
// add.setStatus(AddRequest.STATUS_WAIT);
// add.save();
// }
// }
//
// public static void createAddRequestInBackground(Context ctx, final AVUser user) {
// new MyAsyncTask(ctx) {
// @Override
// protected void doInBack() throws Exception {
// AddRequestService.createAddRequest(user);
// }
//
// @Override
// protected void onSucceed() {
// Utils.toast(R.string.contact_sendRequestSucceed);
// }
// }.execute();
// }
// }
//
// Path: src/com/example/lovetalk/view/ViewHolder.java
// public class ViewHolder {
// public static <T extends View> T findViewById(View view, int id) {
// SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
// if (viewHolder == null) {
// viewHolder = new SparseArray<View>();
// view.setTag(viewHolder);
// }
// View childView = viewHolder.get(id);
// if (childView == null) {
// childView = view.findViewById(id);
// viewHolder.put(id, childView);
// }
// return (T) childView;
// }
// }
| import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.R;
import com.example.lovetalk.service.AddRequestService;
import com.example.lovetalk.view.ViewHolder;
import java.util.List; | package com.example.lovetalk.adapter;
public class AddFriendAdapter extends BaseListAdapter<AVUser> {
Context mContext;
public AddFriendAdapter(Context context, List<AVUser> list) {
super(context, list);
// TODO Auto-generated constructor stub
mContext = context;
}
@Override
public View getView(int position, View conView, ViewGroup parent) {
// TODO Auto-generated method stub
if (conView == null) {
conView = inflater.inflate(R.layout.contact_add_friend_item, null);
}
final AVUser user = datas.get(position);
TextView nameView = ViewHolder.findViewById(conView, R.id.name);
ImageView avatarView = ViewHolder.findViewById(conView, R.id.avatar);
Button addBtn = ViewHolder.findViewById(conView, R.id.add);
// String avatarUrl = contact.getAvatarUrl();
// UserService.displayAvatar(avatarUrl, avatarView);
nameView.setText(user.getUsername());
addBtn.setText(R.string.add);
addBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { | // Path: src/com/example/lovetalk/service/AddRequestService.java
// public class AddRequestService {
// public static int countAddRequests() throws AVException {
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// q.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());
// try {
// return q.count();
// } catch (AVException e) {
// if (e.getCode() == AVException.CACHE_MISS) {
// return 0;
// } else {
// throw e;
// }
// }
// }
//
// public static List<AddRequest> findAddRequests() throws AVException {
// AVUser user = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.include(AddRequest.FROM_USER);
// q.whereEqualTo(AddRequest.TO_USER, user);
// q.orderByDescending("createdAt");
// q.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
// return q.find();
// }
//
// public static boolean hasAddRequest() throws AVException {
// PreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(DemoApplication.context);
// int addRequestN = preferenceMap.getAddRequestN();
// int requestN = countAddRequests();
// if (requestN > addRequestN) {
// return true;
// } else {
// return false;
// }
// }
//
// public static void agreeAddRequest(final AddRequest addRequest, final SaveCallback saveCallback) {
// UserService.addFriend(addRequest.getFromUser().getObjectId(), new SaveCallback() {
// @Override
// public void done(AVException e) {
// if (e != null) {
// if (e.getCode() == AVException.DUPLICATE_VALUE) {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// } else {
// saveCallback.done(e);
// }
// } else {
// addRequest.setStatus(AddRequest.STATUS_DONE);
// addRequest.saveInBackground(saveCallback);
// }
// }
// });
// }
//
// public static void createAddRequest(AVUser toUser) throws Exception {
// AVUser curUser = AVUser.getCurrentUser();
// AVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);
// q.whereEqualTo(AddRequest.FROM_USER, curUser);
// q.whereEqualTo(AddRequest.TO_USER, toUser);
// q.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);
// int count = 0;
// try {
// count = q.count();
// } catch (AVException e) {
// e.printStackTrace();
// if (e.getCode() == AVException.OBJECT_NOT_FOUND) {
// count = 0;
// } else {
// throw e;
// }
// }
// if (count > 0) {
// throw new Exception(DemoApplication.context.getString(R.string.contact_alreadyCreateAddRequest));
// } else {
// AddRequest add = new AddRequest();
// add.setFromUser(curUser);
// add.setToUser(toUser);
// add.setStatus(AddRequest.STATUS_WAIT);
// add.save();
// }
// }
//
// public static void createAddRequestInBackground(Context ctx, final AVUser user) {
// new MyAsyncTask(ctx) {
// @Override
// protected void doInBack() throws Exception {
// AddRequestService.createAddRequest(user);
// }
//
// @Override
// protected void onSucceed() {
// Utils.toast(R.string.contact_sendRequestSucceed);
// }
// }.execute();
// }
// }
//
// Path: src/com/example/lovetalk/view/ViewHolder.java
// public class ViewHolder {
// public static <T extends View> T findViewById(View view, int id) {
// SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
// if (viewHolder == null) {
// viewHolder = new SparseArray<View>();
// view.setTag(viewHolder);
// }
// View childView = viewHolder.get(id);
// if (childView == null) {
// childView = view.findViewById(id);
// viewHolder.put(id, childView);
// }
// return (T) childView;
// }
// }
// Path: src/com/example/lovetalk/adapter/AddFriendAdapter.java
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.R;
import com.example.lovetalk.service.AddRequestService;
import com.example.lovetalk.view.ViewHolder;
import java.util.List;
package com.example.lovetalk.adapter;
public class AddFriendAdapter extends BaseListAdapter<AVUser> {
Context mContext;
public AddFriendAdapter(Context context, List<AVUser> list) {
super(context, list);
// TODO Auto-generated constructor stub
mContext = context;
}
@Override
public View getView(int position, View conView, ViewGroup parent) {
// TODO Auto-generated method stub
if (conView == null) {
conView = inflater.inflate(R.layout.contact_add_friend_item, null);
}
final AVUser user = datas.get(position);
TextView nameView = ViewHolder.findViewById(conView, R.id.name);
ImageView avatarView = ViewHolder.findViewById(conView, R.id.avatar);
Button addBtn = ViewHolder.findViewById(conView, R.id.add);
// String avatarUrl = contact.getAvatarUrl();
// UserService.displayAvatar(avatarUrl, avatarView);
nameView.setText(user.getUsername());
addBtn.setText(R.string.add);
addBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { | AddRequestService.createAddRequestInBackground(mContext, user); |
ga4gh/compliance | cts-java/src/test/java/org/ga4gh/cts/api/TestData.java | // Path: cts-java/src/test/java/org/ga4gh/cts/api/Utils.java
// public static <T> List<T> aSingle(T s) {
// return Collections.singletonList(s);
// }
| import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ga4gh.References.ReferenceSet;
import static org.ga4gh.cts.api.Utils.aSingle; | package org.ga4gh.cts.api;
/**
* This class defines important constants that pertain to and describe the official test data.
* It contains no methods and you cannot instantiate it.
*
* @author Herb Jellinek
*/
public class TestData {
/**
* You can't instantiate one of these.
*/
private TestData() {
}
/**
* The default ID of the dataset that holds the test data. We use something readable so the
* meaning is clear, but in reality the value of this is unlikely to be human-readable.
*/
public static final String DEFAULT_DATASET_ID = "compliance-dataset" ;
/**
* The name of the Java system property that sets the ID of the compliance dataset.
*/
private static final String DATASET_PROP_NAME = "ctk.tgt.dataset_id";
/**
* The name of the reference in the standard test data.
*/
public static final String REFERENCE_NAME = "ref_brca1";
/**
* The start of the reference data.
*/
public static final long REFERENCE_START = 0;
/**
* The end of the reference data.
*/
public static final long REFERENCE_END = 81187;
/**
* The name of the reference used for variant annotation in the standard test data.
*/
public static final String VARIANT_ANNOTATION_REFERENCE_NAME = "1";
/**
* The names of the variant annotation sets used for variant annotation in the standard test data.
*/
public static final List<String> VARIANT_ANNOTATION_SET_NAMES =
Arrays.asList("WASH7P", "OR4F");
/**
* The names of known-good read groups.
*/
public static final SetMultimap<String, String> EXPECTED_READGROUPSET_READGROUP_NAMES =
HashMultimap.create();
static {
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00096",
Arrays.asList("SRR062634",
"SRR062635",
"SRR062641"));
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00099",
Arrays.asList("SRR741411",
"SRR741412"));
//noinspection ArraysAsListWithZeroOrOneArgument
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00101",
Arrays.asList("ERR229776"));
}
/**
* The names of the readgroup sets in the standard compliance dataset.
*/
public static final Multiset<String> EXPECTED_READGROUPSETS_NAMES =
EXPECTED_READGROUPSET_READGROUP_NAMES.keys();
/**
* The names of all known {@link ga4gh.Reads.ReadGroup} objects, obtained from
* {@link #EXPECTED_READGROUPSET_READGROUP_NAMES}.
*/
public static final List<String> EXPECTED_READGROUP_NAMES =
new ArrayList<>(EXPECTED_READGROUPSET_READGROUP_NAMES.values());
/**
* The AssemblyID (really, a name) of the test {@link ReferenceSet}.
*/
public static final String REFERENCESET_ASSEMBLY_ID = "hg37";
/**
* Accession "numbers" (names, really) for the test {@link ReferenceSet}.
*/ | // Path: cts-java/src/test/java/org/ga4gh/cts/api/Utils.java
// public static <T> List<T> aSingle(T s) {
// return Collections.singletonList(s);
// }
// Path: cts-java/src/test/java/org/ga4gh/cts/api/TestData.java
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ga4gh.References.ReferenceSet;
import static org.ga4gh.cts.api.Utils.aSingle;
package org.ga4gh.cts.api;
/**
* This class defines important constants that pertain to and describe the official test data.
* It contains no methods and you cannot instantiate it.
*
* @author Herb Jellinek
*/
public class TestData {
/**
* You can't instantiate one of these.
*/
private TestData() {
}
/**
* The default ID of the dataset that holds the test data. We use something readable so the
* meaning is clear, but in reality the value of this is unlikely to be human-readable.
*/
public static final String DEFAULT_DATASET_ID = "compliance-dataset" ;
/**
* The name of the Java system property that sets the ID of the compliance dataset.
*/
private static final String DATASET_PROP_NAME = "ctk.tgt.dataset_id";
/**
* The name of the reference in the standard test data.
*/
public static final String REFERENCE_NAME = "ref_brca1";
/**
* The start of the reference data.
*/
public static final long REFERENCE_START = 0;
/**
* The end of the reference data.
*/
public static final long REFERENCE_END = 81187;
/**
* The name of the reference used for variant annotation in the standard test data.
*/
public static final String VARIANT_ANNOTATION_REFERENCE_NAME = "1";
/**
* The names of the variant annotation sets used for variant annotation in the standard test data.
*/
public static final List<String> VARIANT_ANNOTATION_SET_NAMES =
Arrays.asList("WASH7P", "OR4F");
/**
* The names of known-good read groups.
*/
public static final SetMultimap<String, String> EXPECTED_READGROUPSET_READGROUP_NAMES =
HashMultimap.create();
static {
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00096",
Arrays.asList("SRR062634",
"SRR062635",
"SRR062641"));
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00099",
Arrays.asList("SRR741411",
"SRR741412"));
//noinspection ArraysAsListWithZeroOrOneArgument
EXPECTED_READGROUPSET_READGROUP_NAMES.putAll("HG00101",
Arrays.asList("ERR229776"));
}
/**
* The names of the readgroup sets in the standard compliance dataset.
*/
public static final Multiset<String> EXPECTED_READGROUPSETS_NAMES =
EXPECTED_READGROUPSET_READGROUP_NAMES.keys();
/**
* The names of all known {@link ga4gh.Reads.ReadGroup} objects, obtained from
* {@link #EXPECTED_READGROUPSET_READGROUP_NAMES}.
*/
public static final List<String> EXPECTED_READGROUP_NAMES =
new ArrayList<>(EXPECTED_READGROUPSET_READGROUP_NAMES.values());
/**
* The AssemblyID (really, a name) of the test {@link ReferenceSet}.
*/
public static final String REFERENCESET_ASSEMBLY_ID = "hg37";
/**
* Accession "numbers" (names, really) for the test {@link ReferenceSet}.
*/ | public static final List<String> REFERENCESET_ACCESSIONS = aSingle("GA4GH_CTS_01"); |
ga4gh/compliance | ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Get.java | // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
| import com.google.protobuf.GeneratedMessage;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.ga4gh.ctk.transport.WireTracker;
import java.util.Map; | package org.ga4gh.ctk.transport.protobuf;
public class Get<T extends GeneratedMessage.Builder> extends Base<T> {
private final String id;
private final Map<String, Object> queryParams;
| // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
// Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Get.java
import com.google.protobuf.GeneratedMessage;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.ga4gh.ctk.transport.WireTracker;
import java.util.Map;
package org.ga4gh.ctk.transport.protobuf;
public class Get<T extends GeneratedMessage.Builder> extends Base<T> {
private final String id;
private final Map<String, Object> queryParams;
| public Get(String urlRoot, String path, String id, Map<String, Object> queryParams, T responseBuilder, WireTracker wireTracker) { |
ga4gh/compliance | ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Post.java | // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
| import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.ga4gh.ctk.transport.WireTracker; | package org.ga4gh.ctk.transport.protobuf;
public class Post<T extends GeneratedMessage.Builder> extends Base<T> {
private final String json;
| // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
// Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Post.java
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.ga4gh.ctk.transport.WireTracker;
package org.ga4gh.ctk.transport.protobuf;
public class Post<T extends GeneratedMessage.Builder> extends Base<T> {
private final String json;
| public Post(String urlRoot, String path, MessageOrBuilder request, T responseBuilder, WireTracker wireTracker) throws InvalidProtocolBufferException { |
ga4gh/compliance | ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Base.java | // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
| import com.google.common.base.CharMatcher;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.exceptions.UnirestException;
import ga4gh.Common;
import org.apache.http.HttpStatus;
import org.ga4gh.ctk.transport.GAWrapperException;
import org.ga4gh.ctk.transport.WireTracker;
import static org.ga4gh.ctk.transport.RespCode.fromInt;
import static org.ga4gh.ctk.transport.TransportUtils.makeUrl;
import static org.slf4j.LoggerFactory.getLogger; | package org.ga4gh.ctk.transport.protobuf;
public abstract class Base<T extends GeneratedMessage.Builder> {
static org.slf4j.Logger log;
/**
* <p>Holds the message traffic sent/received during the entire test run.
* Intended to support test quality/coverage reporting.</p>
*/
private static Table<String, String, Integer> messages;
static {
log = getLogger(Base.class);
messages = HashBasedTable.create();
}
/**
* url root to system-under-test; e.g., "http://localhost:8000"
*/
private final String urlRoot;
private final String path;
| // Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/WireTracker.java
// public class WireTracker {
// final static Logger log = getLogger(WireTracker.class);
//
// /**
// * <p>The target url with which this WireTracker communicated.</p>
// */
// public String theUrl;
//
// /**
// * <p>The string BODY sent to the target.</p>
// */
// public String bodySent;
//
// /**
// * <p>The string BODY received from the target</p>
// */
// public String bodyReceived;
//
// private GAException gae;
//
// private String gaeMessage; // convenience and in case non-parseable
//
// private int gaeErrorCode; // convenience and in case non-parseable
//
// /**
// * <p>Returns true if and only if a {@link GAException} was received on this interaction,
// * AND it was parsable.</p>
// * <p>If it's non-parseable then the gaeMessage field
// * will hold the returned BODY (same as the bodyReceived field) and the
// * gaeErrorCode will be set to -1</p>
// *
// * @return true if we received a {@link GAException} on this interaction
// */
// @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
// public boolean gotParseableGAE() {
// return getGae() != null;
// }
//
// private boolean parseableGae = false;
//
// RespCode responseStatus;
//
// public int getErrorCode() {
// return gaeErrorCode;
// }
//
// public String getMessage() {
// return gaeMessage;
// }
//
// public GAException getGae() {
// if (responseStatus != RespCode.OK) {
// // parse the received body
// Gson gson = new Gson();
// try {
// gae = gson.fromJson(bodyReceived, GAException.class);
// gaeMessage = gae.getMessage();
// gaeErrorCode = gae.getErrorCode();
// } catch (Exception e) {
// log.warn("Parse failure on GAException: BODY < " + bodyReceived + " > " + e
// .toString());
// gaeErrorCode = -1;
// gaeMessage = bodyReceived;
// parseableGae = false;
// gae = null;
// }
// }
// return gae;
// }
//
// public RespCode getResponseStatus() {
// return responseStatus;
// }
//
// public void setResponseStatus(RespCode responseStatus) {
// this.responseStatus = responseStatus;
// }
// }
// Path: ctk-transport/src/main/java/org/ga4gh/ctk/transport/protobuf/Base.java
import com.google.common.base.CharMatcher;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.protobuf.GeneratedMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.exceptions.UnirestException;
import ga4gh.Common;
import org.apache.http.HttpStatus;
import org.ga4gh.ctk.transport.GAWrapperException;
import org.ga4gh.ctk.transport.WireTracker;
import static org.ga4gh.ctk.transport.RespCode.fromInt;
import static org.ga4gh.ctk.transport.TransportUtils.makeUrl;
import static org.slf4j.LoggerFactory.getLogger;
package org.ga4gh.ctk.transport.protobuf;
public abstract class Base<T extends GeneratedMessage.Builder> {
static org.slf4j.Logger log;
/**
* <p>Holds the message traffic sent/received during the entire test run.
* Intended to support test quality/coverage reporting.</p>
*/
private static Table<String, String, Integer> messages;
static {
log = getLogger(Base.class);
messages = HashBasedTable.create();
}
/**
* url root to system-under-test; e.g., "http://localhost:8000"
*/
private final String urlRoot;
private final String path;
| final WireTracker wireTracker; |
kb10uy/Tencocoa | app/src/main/java/org/kb10uy/tencocoa/UserInformationFragment.java | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/views/TencocoaServiceProvider.java
// public interface TencocoaServiceProvider {
// TencocoaWritePermissionService getWritePermissionService();
// TencocoaReadPermissionService getReadPermissionService();
// TencocoaStreamingService getStreamingService();
// boolean isWriteBound();
// boolean isReadBound();
// boolean isStreamingBound();
// }
| import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.common.base.Strings;
import com.twitter.Extractor;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.views.TencocoaServiceProvider;
import java.util.List;
import twitter4j.Status;
import twitter4j.User; | package org.kb10uy.tencocoa;
public class UserInformationFragment extends Fragment {
private ViewPager mViewPager;
private UserInformationFragmentPagerAdapter mAdapter;
private User currentUser; | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/views/TencocoaServiceProvider.java
// public interface TencocoaServiceProvider {
// TencocoaWritePermissionService getWritePermissionService();
// TencocoaReadPermissionService getReadPermissionService();
// TencocoaStreamingService getStreamingService();
// boolean isWriteBound();
// boolean isReadBound();
// boolean isStreamingBound();
// }
// Path: app/src/main/java/org/kb10uy/tencocoa/UserInformationFragment.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.common.base.Strings;
import com.twitter.Extractor;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.views.TencocoaServiceProvider;
import java.util.List;
import twitter4j.Status;
import twitter4j.User;
package org.kb10uy.tencocoa;
public class UserInformationFragment extends Fragment {
private ViewPager mViewPager;
private UserInformationFragmentPagerAdapter mAdapter;
private User currentUser; | private TencocoaServiceProvider mProvider; |
kb10uy/Tencocoa | app/src/main/java/org/kb10uy/tencocoa/TencocoaWritePermissionService.java | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterHelper.java
// public final class TwitterHelper {
//
// public static Twitter getTwitterInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// Twitter tw = new TwitterFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static TwitterStream getTwitterStreamInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// TwitterStream tw = new TwitterStreamFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static long[] convertMediaIds(List<UploadedMedia> media) {
// long[] result = new long[media.size()];
// for (int i = 0; i < media.size(); i++) {
// result[i]=media.get(i).getMediaId();
// }
// return result;
// }
//
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.widget.Toast;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.model.TwitterHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken; | package org.kb10uy.tencocoa;
public class TencocoaWritePermissionService extends Service {
private static final int TENCOCOA_WRITE_PERMISSION_NOTIFICATION_ID = 0xC0C0A3;
| // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterHelper.java
// public final class TwitterHelper {
//
// public static Twitter getTwitterInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// Twitter tw = new TwitterFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static TwitterStream getTwitterStreamInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// TwitterStream tw = new TwitterStreamFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static long[] convertMediaIds(List<UploadedMedia> media) {
// long[] result = new long[media.size()];
// for (int i = 0; i < media.size(); i++) {
// result[i]=media.get(i).getMediaId();
// }
// return result;
// }
//
// }
// Path: app/src/main/java/org/kb10uy/tencocoa/TencocoaWritePermissionService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.widget.Toast;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.model.TwitterHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
package org.kb10uy.tencocoa;
public class TencocoaWritePermissionService extends Service {
private static final int TENCOCOA_WRITE_PERMISSION_NOTIFICATION_ID = 0xC0C0A3;
| private TwitterAccountInformation currentUser; |
kb10uy/Tencocoa | app/src/main/java/org/kb10uy/tencocoa/TencocoaWritePermissionService.java | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterHelper.java
// public final class TwitterHelper {
//
// public static Twitter getTwitterInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// Twitter tw = new TwitterFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static TwitterStream getTwitterStreamInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// TwitterStream tw = new TwitterStreamFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static long[] convertMediaIds(List<UploadedMedia> media) {
// long[] result = new long[media.size()];
// for (int i = 0; i < media.size(); i++) {
// result[i]=media.get(i).getMediaId();
// }
// return result;
// }
//
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.widget.Toast;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.model.TwitterHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken; |
public void pushImages(List<Uri> uris) {
mPendingMediaUris.addAll(uris);
}
public void updateStatus(StatusUpdate status) {
AsyncTask<StatusUpdate, Void, String> task = new AsyncTask<StatusUpdate, Void, String>() {
@Override
protected String doInBackground(StatusUpdate... params) {
if (currentUser == null) return getString(R.string.notification_network_unavailable);
try {
StatusUpdate target = params[0];
if (mPendingMediaUris.size() >= 0) {
List<UploadedMedia> media = new ArrayList<>();
for (Uri u : mPendingMediaUris) {
String path = "";
if (u.getScheme().equals("content")) {
ContentResolver contentResolver = getApplicationContext().getContentResolver();
Cursor cursor = contentResolver.query(u, new String[]{MediaStore.MediaColumns.DATA}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
path = cursor.getString(0);
cursor.close();
}
} else {
path = u.getPath();
}
media.add(mTwitter.uploadMedia(new File(path)));
}
mPendingMediaUris.clear(); | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterAccountInformation.java
// public class TwitterAccountInformation implements Serializable {
// private static final long serialVersionUID = 2591925210205947107L;
//
// private long userId;
// private String screenName;
// private AccessToken token;
//
// public TwitterAccountInformation(AccessToken token) {
// userId = token.getUserId();
// screenName = token.getScreenName();
// this.token = token;
// }
//
// public AccessToken getAccessToken() {
// return token;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public long getUserId() {
// return userId;
// }
// }
//
// Path: app/src/main/java/org/kb10uy/tencocoa/model/TwitterHelper.java
// public final class TwitterHelper {
//
// public static Twitter getTwitterInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// Twitter tw = new TwitterFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static TwitterStream getTwitterStreamInstance(String ck, String cs, AccessToken token) {
// Configuration tencocoaConfig = new ConfigurationBuilder()
// .setGZIPEnabled(true)
// .setDispatcherImpl(TencocoaDispatcher.class.getName())
// .setOAuthConsumerKey(ck)
// .setOAuthConsumerSecret(cs)
// .setOAuthAccessToken(token.getToken())
// .setOAuthAccessTokenSecret(token.getTokenSecret())
// .build();
// TwitterStream tw = new TwitterStreamFactory(tencocoaConfig).getInstance();
// return tw;
// }
//
// public static long[] convertMediaIds(List<UploadedMedia> media) {
// long[] result = new long[media.size()];
// for (int i = 0; i < media.size(); i++) {
// result[i]=media.get(i).getMediaId();
// }
// return result;
// }
//
// }
// Path: app/src/main/java/org/kb10uy/tencocoa/TencocoaWritePermissionService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.widget.Toast;
import org.kb10uy.tencocoa.model.TwitterAccountInformation;
import org.kb10uy.tencocoa.model.TwitterHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.UploadedMedia;
import twitter4j.User;
import twitter4j.auth.AccessToken;
public void pushImages(List<Uri> uris) {
mPendingMediaUris.addAll(uris);
}
public void updateStatus(StatusUpdate status) {
AsyncTask<StatusUpdate, Void, String> task = new AsyncTask<StatusUpdate, Void, String>() {
@Override
protected String doInBackground(StatusUpdate... params) {
if (currentUser == null) return getString(R.string.notification_network_unavailable);
try {
StatusUpdate target = params[0];
if (mPendingMediaUris.size() >= 0) {
List<UploadedMedia> media = new ArrayList<>();
for (Uri u : mPendingMediaUris) {
String path = "";
if (u.getScheme().equals("content")) {
ContentResolver contentResolver = getApplicationContext().getContentResolver();
Cursor cursor = contentResolver.query(u, new String[]{MediaStore.MediaColumns.DATA}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
path = cursor.getString(0);
cursor.close();
}
} else {
path = u.getPath();
}
media.add(mTwitter.uploadMedia(new File(path)));
}
mPendingMediaUris.clear(); | long[] ids = TwitterHelper.convertMediaIds(media); |
kb10uy/Tencocoa | app/src/main/java/org/kb10uy/tencocoa/settings/LicenseActivity.java | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TencocoaHelper.java
// public class TencocoaHelper {
// public static final char numberSuffixes[] = new char[]{' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
// public static final int translatedErrors[] = new int[]{32, 34, 64, 68, 88, 89, 92, 130, 131, 135, 161, 179, 185, 187, 215, 226, 231, 251, 261, 271, 272, 354};
// private static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
//
// public static boolean serializeObjectToFile(Serializable object, FileOutputStream output) {
// try {
// ObjectOutputStream serializer = new ObjectOutputStream(output);
// serializer.writeObject(object);
// return true;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public static <T> T deserializeObjectFromFile(FileInputStream input) {
// try {
// ObjectInputStream deserializer = new ObjectInputStream(input);
// return (T) deserializer.readObject();
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return null;
// }
// }
//
// public static String getCompressedNumberString(int num) {
// DecimalFormat df = new DecimalFormat("0.0");
// double tg = num;
// int si = 0;
// while (tg > 1000) {
// tg /= 1000.0;
// si++;
// }
// if ((int) tg == num) {
// df = new DecimalFormat("0");
// } else {
// df = new DecimalFormat("0.0");
// }
// StringBuilder sb = new StringBuilder();
// sb.append(df.format(tg));
// sb.append(numberSuffixes[si]);
// return sb.toString();
// }
//
// public static String getRelativeTimeString(Date targetDate) {
// Duration d = new Duration(new DateTime(targetDate), new DateTime(new Date()));
// long relative = d.getStandardSeconds();
// if (relative < 20) return "now";
// if (relative < 60) return Long.toString(relative) + "s";
// if ((relative = d.getStandardMinutes()) < 60) return Long.toString(relative) + "m";
// if ((relative = d.getStandardHours()) < 24) return Long.toString(relative) + "h";
// relative = d.getStandardDays();
// return Long.toString(relative) + "d";
// }
//
// public static String getAbsoluteTimeString(Date targetDate) {
// return mDateFormat.format(targetDate);
// }
//
// public static void setCurrentTheme(Context ctx, String theme) {
// switch (theme) {
// case "Black":
// ctx.setTheme(R.style.Black);
// break;
// case "White":
// ctx.setTheme(R.style.White);
// break;
// case "Hinanawi":
// ctx.setTheme(R.style.Hinanawi);
// break;
// case "Hoto":
// ctx.setTheme(R.style.Hoto);
// break;
// case "Komichi":
// ctx.setTheme(R.style.Komichi);
// break;
// case "Witch":
// ctx.setTheme(R.style.Witch);
// break;
// case "Tomori":
// ctx.setTheme(R.style.Tomori);
// break;
// }
// }
//
// public static String createReplyTemplate(TencocoaStatus status) {
// StringBuilder builder = new StringBuilder();
// Status target = status.getShowingStatus();
// User tweeter = target.getUser();
// builder.append("@").append(target.getUser().getScreenName()).append(" ");
// UserMentionEntity[] entities = target.getUserMentionEntities();
// if (entities == null) return builder.toString();
// for (UserMentionEntity e : entities) {
// if (tweeter.getId() == e.getId()) continue;
// builder.append("@").append(e.getScreenName()).append(" ");
// }
// return builder.toString();
// }
//
// public static void Run(Runnable r) {
// new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... params) {
// r.run();
// return null;
// }
// }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// }
//
// public static String getTwitterErrorMessage(Context ctx, TwitterException ex) {
// if (Ints.contains(translatedErrors, ex.getErrorCode())) return ctx.getString(ctx.getResources().getIdentifier("text", "string", ctx.getPackageName()));
// return ex.getErrorMessage();
// }
// }
| import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import org.kb10uy.tencocoa.R;
import org.kb10uy.tencocoa.model.TencocoaHelper; | package org.kb10uy.tencocoa.settings;
public class LicenseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); | // Path: app/src/main/java/org/kb10uy/tencocoa/model/TencocoaHelper.java
// public class TencocoaHelper {
// public static final char numberSuffixes[] = new char[]{' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
// public static final int translatedErrors[] = new int[]{32, 34, 64, 68, 88, 89, 92, 130, 131, 135, 161, 179, 185, 187, 215, 226, 231, 251, 261, 271, 272, 354};
// private static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
//
// public static boolean serializeObjectToFile(Serializable object, FileOutputStream output) {
// try {
// ObjectOutputStream serializer = new ObjectOutputStream(output);
// serializer.writeObject(object);
// return true;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public static <T> T deserializeObjectFromFile(FileInputStream input) {
// try {
// ObjectInputStream deserializer = new ObjectInputStream(input);
// return (T) deserializer.readObject();
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// return null;
// }
// }
//
// public static String getCompressedNumberString(int num) {
// DecimalFormat df = new DecimalFormat("0.0");
// double tg = num;
// int si = 0;
// while (tg > 1000) {
// tg /= 1000.0;
// si++;
// }
// if ((int) tg == num) {
// df = new DecimalFormat("0");
// } else {
// df = new DecimalFormat("0.0");
// }
// StringBuilder sb = new StringBuilder();
// sb.append(df.format(tg));
// sb.append(numberSuffixes[si]);
// return sb.toString();
// }
//
// public static String getRelativeTimeString(Date targetDate) {
// Duration d = new Duration(new DateTime(targetDate), new DateTime(new Date()));
// long relative = d.getStandardSeconds();
// if (relative < 20) return "now";
// if (relative < 60) return Long.toString(relative) + "s";
// if ((relative = d.getStandardMinutes()) < 60) return Long.toString(relative) + "m";
// if ((relative = d.getStandardHours()) < 24) return Long.toString(relative) + "h";
// relative = d.getStandardDays();
// return Long.toString(relative) + "d";
// }
//
// public static String getAbsoluteTimeString(Date targetDate) {
// return mDateFormat.format(targetDate);
// }
//
// public static void setCurrentTheme(Context ctx, String theme) {
// switch (theme) {
// case "Black":
// ctx.setTheme(R.style.Black);
// break;
// case "White":
// ctx.setTheme(R.style.White);
// break;
// case "Hinanawi":
// ctx.setTheme(R.style.Hinanawi);
// break;
// case "Hoto":
// ctx.setTheme(R.style.Hoto);
// break;
// case "Komichi":
// ctx.setTheme(R.style.Komichi);
// break;
// case "Witch":
// ctx.setTheme(R.style.Witch);
// break;
// case "Tomori":
// ctx.setTheme(R.style.Tomori);
// break;
// }
// }
//
// public static String createReplyTemplate(TencocoaStatus status) {
// StringBuilder builder = new StringBuilder();
// Status target = status.getShowingStatus();
// User tweeter = target.getUser();
// builder.append("@").append(target.getUser().getScreenName()).append(" ");
// UserMentionEntity[] entities = target.getUserMentionEntities();
// if (entities == null) return builder.toString();
// for (UserMentionEntity e : entities) {
// if (tweeter.getId() == e.getId()) continue;
// builder.append("@").append(e.getScreenName()).append(" ");
// }
// return builder.toString();
// }
//
// public static void Run(Runnable r) {
// new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... params) {
// r.run();
// return null;
// }
// }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// }
//
// public static String getTwitterErrorMessage(Context ctx, TwitterException ex) {
// if (Ints.contains(translatedErrors, ex.getErrorCode())) return ctx.getString(ctx.getResources().getIdentifier("text", "string", ctx.getPackageName()));
// return ex.getErrorMessage();
// }
// }
// Path: app/src/main/java/org/kb10uy/tencocoa/settings/LicenseActivity.java
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import org.kb10uy.tencocoa.R;
import org.kb10uy.tencocoa.model.TencocoaHelper;
package org.kb10uy.tencocoa.settings;
public class LicenseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); | TencocoaHelper.setCurrentTheme(this, pref.getString(getString(R.string.preference_appearance_theme), "Black")); |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/smb/SmbDeployerRunnerInfo.java | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
| import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.smb;
class SmbDeployerRunnerInfo implements AgentBuildRunnerInfo {
@NotNull
@Override
public String getType() { | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/smb/SmbDeployerRunnerInfo.java
import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.smb;
class SmbDeployerRunnerInfo implements AgentBuildRunnerInfo {
@NotNull
@Override
public String getType() { | return DeployerRunnerConstants.SMB_RUN_TYPE; |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/ssh/BaseSSHTransferTest.java | // Path: deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/util/DeployTestUtils.java
// public class DeployTestUtils {
// public static void runProcess(final BuildProcess process, final int timeout) throws RunBuildException {
// process.start();
// new WaitFor(timeout) {
// @Override
// protected boolean condition() {
// return process.isFinished();
// }
// };
// assertThat(process.isFinished()).describedAs("Failed to finish test in time").isTrue();
// assertThat(process.waitFor()).isEqualTo(BuildFinishedStatus.FINISHED_SUCCESS);
// }
//
// public static ArtifactsCollection buildArtifactsCollection(final TempFilesFactory tempFiles, String... destinationDirs) throws IOException {
//
// final Map<File, String> filePathMap = new HashMap<File, String>();
// String dirTo = "dirTo";
// for (String destinationDir : destinationDirs) {
// dirTo = destinationDir;
// final File content = tempFiles.createTempFile(100);
// filePathMap.put(content, destinationDir);
// }
// return new ArtifactsCollection("dirFrom/**", dirTo, filePathMap);
// }
//
// public static void assertCollectionsTransferred(File remoteBase, List<ArtifactsCollection> artifactsCollections) throws IOException {
//
// for (ArtifactsCollection artifactsCollection : artifactsCollections) {
// for (Map.Entry<File, String> fileStringEntry : artifactsCollection.getFilePathMap().entrySet()) {
// final File source = fileStringEntry.getKey();
// final String relativePath = fileStringEntry.getValue();
// final String targetPath = relativePath + (StringUtil.isNotEmpty(relativePath) ? File.separator : "") + source.getName();
// final File target;
// if (new File(targetPath).isAbsolute()) {
// target = new File(targetPath);
// } else {
// target = new File(remoteBase, targetPath);
// }
// assertTrue(target.exists(), "Destination file [" + targetPath + "] does not exist");
// assertEquals(FileUtil.readText(target), FileUtil.readText(source), "wrong content");
// }
// }
// }
//
// public interface TempFilesFactory {
// File createTempFile(int size) throws IOException;
// }
// }
| import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.deployer.agent.util.DeployTestUtils;
import org.testng.annotations.Test;
import java.io.File;
import static org.testng.Assert.assertTrue; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ssh;
/**
* Created by Nikita.Skvortsov
* Date: 10/3/12, 3:13 PM
*/
public abstract class BaseSSHTransferTest extends BaseSSHTest {
@Test
public void testSimpleTransfer() throws Exception { | // Path: deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/util/DeployTestUtils.java
// public class DeployTestUtils {
// public static void runProcess(final BuildProcess process, final int timeout) throws RunBuildException {
// process.start();
// new WaitFor(timeout) {
// @Override
// protected boolean condition() {
// return process.isFinished();
// }
// };
// assertThat(process.isFinished()).describedAs("Failed to finish test in time").isTrue();
// assertThat(process.waitFor()).isEqualTo(BuildFinishedStatus.FINISHED_SUCCESS);
// }
//
// public static ArtifactsCollection buildArtifactsCollection(final TempFilesFactory tempFiles, String... destinationDirs) throws IOException {
//
// final Map<File, String> filePathMap = new HashMap<File, String>();
// String dirTo = "dirTo";
// for (String destinationDir : destinationDirs) {
// dirTo = destinationDir;
// final File content = tempFiles.createTempFile(100);
// filePathMap.put(content, destinationDir);
// }
// return new ArtifactsCollection("dirFrom/**", dirTo, filePathMap);
// }
//
// public static void assertCollectionsTransferred(File remoteBase, List<ArtifactsCollection> artifactsCollections) throws IOException {
//
// for (ArtifactsCollection artifactsCollection : artifactsCollections) {
// for (Map.Entry<File, String> fileStringEntry : artifactsCollection.getFilePathMap().entrySet()) {
// final File source = fileStringEntry.getKey();
// final String relativePath = fileStringEntry.getValue();
// final String targetPath = relativePath + (StringUtil.isNotEmpty(relativePath) ? File.separator : "") + source.getName();
// final File target;
// if (new File(targetPath).isAbsolute()) {
// target = new File(targetPath);
// } else {
// target = new File(remoteBase, targetPath);
// }
// assertTrue(target.exists(), "Destination file [" + targetPath + "] does not exist");
// assertEquals(FileUtil.readText(target), FileUtil.readText(source), "wrong content");
// }
// }
// }
//
// public interface TempFilesFactory {
// File createTempFile(int size) throws IOException;
// }
// }
// Path: deploy-runner-agent/src/test/java/jetbrains/buildServer/deployer/agent/ssh/BaseSSHTransferTest.java
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.deployer.agent.util.DeployTestUtils;
import org.testng.annotations.Test;
import java.io.File;
import static org.testng.Assert.assertTrue;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ssh;
/**
* Created by Nikita.Skvortsov
* Date: 10/3/12, 3:13 PM
*/
public abstract class BaseSSHTransferTest extends BaseSSHTest {
@Test
public void testSimpleTransfer() throws Exception { | myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2")); |
JetBrains/teamcity-deployer-plugin | deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SSHDeployerPropertiesProcessor.java | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/SSHRunnerConstants.java
// public class SSHRunnerConstants {
//
// public static final String SSH_EXEC_RUN_TYPE = "ssh-exec-runner";
//
// @Deprecated
// public static final String PARAM_HOST = "jetbrains.buildServer.sshexec.host";
// public static final String PARAM_PORT = "jetbrains.buildServer.sshexec.port";
// @Deprecated
// public static final String PARAM_USERNAME = "jetbrains.buildServer.sshexec.username";
// @Deprecated
// public static final String PARAM_PASSWORD = "jetbrains.buildServer.sshexec.password";
// public static final String PARAM_KEYFILE = "jetbrains.buildServer.sshexec.keyFile";
// public static final String PARAM_UPLOADED_KEY_ID = "jetbrains.buildServer.sshexec.key.id";
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.sshexec.authMethod";
// public static final String PARAM_COMMAND = "jetbrains.buildServer.sshexec.command";
// public static final String PARAM_PTY = "jetbrains.buildServer.sshexec.pty";
//
// public static final String PARAM_TRANSPORT = "jetbrains.buildServer.deployer.ssh.transport";
//
// public static final String TRANSPORT_SCP = "jetbrains.buildServer.deployer.ssh.transport.scp";
// public static final String TRANSPORT_SFTP = "jetbrains.buildServer.deployer.ssh.transport.sftp";
// public static final String AUTH_METHOD_DEFAULT_KEY = "DEFAULT_KEY";
// public static final String AUTH_METHOD_CUSTOM_KEY = "CUSTOM_KEY";
// public static final String AUTH_METHOD_USERNAME_PWD = "PWD";
// public static final String AUTH_METHOD_SSH_AGENT = "SSH_AGENT";
// public static final String AUTH_METHOD_UPLOADED_KEY = "UPLOADED_KEY";
//
// public static final String ENABLE_SSH_AGENT_FORWARDING = "teamcity.deployer.ssh.enableAgentForwarding";
//
// public String getTransportType() {
// return PARAM_TRANSPORT;
// }
//
// public Map<String, String> getTransportTypeValues() {
// final Map<String, String> result = new LinkedHashMap<String, String>();
// result.put(TRANSPORT_SCP, "SCP");
// result.put(TRANSPORT_SFTP, "SFTP");
// return result;
// }
//
//
// }
| import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.util.StringUtil;
import java.util.Collection;
import java.util.Map; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
/**
* Created by Nikita.Skvortsov
* date: 13.02.14.
*/
class SSHDeployerPropertiesProcessor extends DeployerPropertiesProcessor {
@Override
public Collection<InvalidProperty> process(Map<String, String> properties) {
Collection<InvalidProperty> result = super.process(properties); | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/SSHRunnerConstants.java
// public class SSHRunnerConstants {
//
// public static final String SSH_EXEC_RUN_TYPE = "ssh-exec-runner";
//
// @Deprecated
// public static final String PARAM_HOST = "jetbrains.buildServer.sshexec.host";
// public static final String PARAM_PORT = "jetbrains.buildServer.sshexec.port";
// @Deprecated
// public static final String PARAM_USERNAME = "jetbrains.buildServer.sshexec.username";
// @Deprecated
// public static final String PARAM_PASSWORD = "jetbrains.buildServer.sshexec.password";
// public static final String PARAM_KEYFILE = "jetbrains.buildServer.sshexec.keyFile";
// public static final String PARAM_UPLOADED_KEY_ID = "jetbrains.buildServer.sshexec.key.id";
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.sshexec.authMethod";
// public static final String PARAM_COMMAND = "jetbrains.buildServer.sshexec.command";
// public static final String PARAM_PTY = "jetbrains.buildServer.sshexec.pty";
//
// public static final String PARAM_TRANSPORT = "jetbrains.buildServer.deployer.ssh.transport";
//
// public static final String TRANSPORT_SCP = "jetbrains.buildServer.deployer.ssh.transport.scp";
// public static final String TRANSPORT_SFTP = "jetbrains.buildServer.deployer.ssh.transport.sftp";
// public static final String AUTH_METHOD_DEFAULT_KEY = "DEFAULT_KEY";
// public static final String AUTH_METHOD_CUSTOM_KEY = "CUSTOM_KEY";
// public static final String AUTH_METHOD_USERNAME_PWD = "PWD";
// public static final String AUTH_METHOD_SSH_AGENT = "SSH_AGENT";
// public static final String AUTH_METHOD_UPLOADED_KEY = "UPLOADED_KEY";
//
// public static final String ENABLE_SSH_AGENT_FORWARDING = "teamcity.deployer.ssh.enableAgentForwarding";
//
// public String getTransportType() {
// return PARAM_TRANSPORT;
// }
//
// public Map<String, String> getTransportTypeValues() {
// final Map<String, String> result = new LinkedHashMap<String, String>();
// result.put(TRANSPORT_SCP, "SCP");
// result.put(TRANSPORT_SFTP, "SFTP");
// return result;
// }
//
//
// }
// Path: deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SSHDeployerPropertiesProcessor.java
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.util.StringUtil;
import java.util.Collection;
import java.util.Map;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
/**
* Created by Nikita.Skvortsov
* date: 13.02.14.
*/
class SSHDeployerPropertiesProcessor extends DeployerPropertiesProcessor {
@Override
public Collection<InvalidProperty> process(Map<String, String> properties) {
Collection<InvalidProperty> result = super.process(properties); | if (StringUtil.isEmptyOrSpaces(properties.get(DeployerRunnerConstants.PARAM_USERNAME)) && |
JetBrains/teamcity-deployer-plugin | deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SSHDeployerPropertiesProcessor.java | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/SSHRunnerConstants.java
// public class SSHRunnerConstants {
//
// public static final String SSH_EXEC_RUN_TYPE = "ssh-exec-runner";
//
// @Deprecated
// public static final String PARAM_HOST = "jetbrains.buildServer.sshexec.host";
// public static final String PARAM_PORT = "jetbrains.buildServer.sshexec.port";
// @Deprecated
// public static final String PARAM_USERNAME = "jetbrains.buildServer.sshexec.username";
// @Deprecated
// public static final String PARAM_PASSWORD = "jetbrains.buildServer.sshexec.password";
// public static final String PARAM_KEYFILE = "jetbrains.buildServer.sshexec.keyFile";
// public static final String PARAM_UPLOADED_KEY_ID = "jetbrains.buildServer.sshexec.key.id";
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.sshexec.authMethod";
// public static final String PARAM_COMMAND = "jetbrains.buildServer.sshexec.command";
// public static final String PARAM_PTY = "jetbrains.buildServer.sshexec.pty";
//
// public static final String PARAM_TRANSPORT = "jetbrains.buildServer.deployer.ssh.transport";
//
// public static final String TRANSPORT_SCP = "jetbrains.buildServer.deployer.ssh.transport.scp";
// public static final String TRANSPORT_SFTP = "jetbrains.buildServer.deployer.ssh.transport.sftp";
// public static final String AUTH_METHOD_DEFAULT_KEY = "DEFAULT_KEY";
// public static final String AUTH_METHOD_CUSTOM_KEY = "CUSTOM_KEY";
// public static final String AUTH_METHOD_USERNAME_PWD = "PWD";
// public static final String AUTH_METHOD_SSH_AGENT = "SSH_AGENT";
// public static final String AUTH_METHOD_UPLOADED_KEY = "UPLOADED_KEY";
//
// public static final String ENABLE_SSH_AGENT_FORWARDING = "teamcity.deployer.ssh.enableAgentForwarding";
//
// public String getTransportType() {
// return PARAM_TRANSPORT;
// }
//
// public Map<String, String> getTransportTypeValues() {
// final Map<String, String> result = new LinkedHashMap<String, String>();
// result.put(TRANSPORT_SCP, "SCP");
// result.put(TRANSPORT_SFTP, "SFTP");
// return result;
// }
//
//
// }
| import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.util.StringUtil;
import java.util.Collection;
import java.util.Map; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
/**
* Created by Nikita.Skvortsov
* date: 13.02.14.
*/
class SSHDeployerPropertiesProcessor extends DeployerPropertiesProcessor {
@Override
public Collection<InvalidProperty> process(Map<String, String> properties) {
Collection<InvalidProperty> result = super.process(properties);
if (StringUtil.isEmptyOrSpaces(properties.get(DeployerRunnerConstants.PARAM_USERNAME)) && | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/SSHRunnerConstants.java
// public class SSHRunnerConstants {
//
// public static final String SSH_EXEC_RUN_TYPE = "ssh-exec-runner";
//
// @Deprecated
// public static final String PARAM_HOST = "jetbrains.buildServer.sshexec.host";
// public static final String PARAM_PORT = "jetbrains.buildServer.sshexec.port";
// @Deprecated
// public static final String PARAM_USERNAME = "jetbrains.buildServer.sshexec.username";
// @Deprecated
// public static final String PARAM_PASSWORD = "jetbrains.buildServer.sshexec.password";
// public static final String PARAM_KEYFILE = "jetbrains.buildServer.sshexec.keyFile";
// public static final String PARAM_UPLOADED_KEY_ID = "jetbrains.buildServer.sshexec.key.id";
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.sshexec.authMethod";
// public static final String PARAM_COMMAND = "jetbrains.buildServer.sshexec.command";
// public static final String PARAM_PTY = "jetbrains.buildServer.sshexec.pty";
//
// public static final String PARAM_TRANSPORT = "jetbrains.buildServer.deployer.ssh.transport";
//
// public static final String TRANSPORT_SCP = "jetbrains.buildServer.deployer.ssh.transport.scp";
// public static final String TRANSPORT_SFTP = "jetbrains.buildServer.deployer.ssh.transport.sftp";
// public static final String AUTH_METHOD_DEFAULT_KEY = "DEFAULT_KEY";
// public static final String AUTH_METHOD_CUSTOM_KEY = "CUSTOM_KEY";
// public static final String AUTH_METHOD_USERNAME_PWD = "PWD";
// public static final String AUTH_METHOD_SSH_AGENT = "SSH_AGENT";
// public static final String AUTH_METHOD_UPLOADED_KEY = "UPLOADED_KEY";
//
// public static final String ENABLE_SSH_AGENT_FORWARDING = "teamcity.deployer.ssh.enableAgentForwarding";
//
// public String getTransportType() {
// return PARAM_TRANSPORT;
// }
//
// public Map<String, String> getTransportTypeValues() {
// final Map<String, String> result = new LinkedHashMap<String, String>();
// result.put(TRANSPORT_SCP, "SCP");
// result.put(TRANSPORT_SFTP, "SFTP");
// return result;
// }
//
//
// }
// Path: deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SSHDeployerPropertiesProcessor.java
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.util.StringUtil;
import java.util.Collection;
import java.util.Map;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
/**
* Created by Nikita.Skvortsov
* date: 13.02.14.
*/
class SSHDeployerPropertiesProcessor extends DeployerPropertiesProcessor {
@Override
public Collection<InvalidProperty> process(Map<String, String> properties) {
Collection<InvalidProperty> result = super.process(properties);
if (StringUtil.isEmptyOrSpaces(properties.get(DeployerRunnerConstants.PARAM_USERNAME)) && | !SSHRunnerConstants.AUTH_METHOD_DEFAULT_KEY.equals(properties.get(SSHRunnerConstants.PARAM_AUTH_METHOD))) { |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/ftp/FtpDeployerRunner.java | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/base/BaseDeployerRunner.java
// public abstract class BaseDeployerRunner implements AgentBuildRunner {
// protected final ExtensionHolder myExtensionHolder;
//
// public BaseDeployerRunner(@NotNull final ExtensionHolder extensionHolder) {
// myExtensionHolder = extensionHolder;
// }
//
// @NotNull
// @Override
// public BuildProcess createBuildProcess(@NotNull final AgentRunningBuild runningBuild,
// @NotNull final BuildRunnerContext context) throws RunBuildException {
//
// final Map<String, String> runnerParameters = context.getRunnerParameters();
// final String username = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_USERNAME));
// final String password = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_PASSWORD));
// final String target = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_TARGET_URL));
// final String sourcePaths = runnerParameters.get(DeployerRunnerConstants.PARAM_SOURCE_PATH);
//
// final Collection<ArtifactsPreprocessor> preprocessors = myExtensionHolder.getExtensions(ArtifactsPreprocessor.class);
//
// final ArtifactsBuilder builder = new ArtifactsBuilder();
// builder.setPreprocessors(preprocessors);
// builder.setBaseDir(runningBuild.getCheckoutDirectory());
// builder.setArtifactsPaths(sourcePaths);
//
// final List<ArtifactsCollection> artifactsCollections = builder.build();
//
// return getDeployerProcess(context, username, password, target, artifactsCollections);
// }
//
// protected abstract BuildProcess getDeployerProcess(@NotNull final BuildRunnerContext context,
// @NotNull final String username,
// @NotNull final String password,
// @NotNull final String target,
// @NotNull final List<ArtifactsCollection> artifactsCollections) throws RunBuildException;
//
// @NotNull
// @Override
// public abstract AgentBuildRunnerInfo getRunnerInfo();
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/FTPRunnerConstants.java
// public class FTPRunnerConstants {
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.deployer.ftp.authMethod";
// public static final String PARAM_TRANSFER_MODE = "jetbrains.buildServer.deployer.ftp.transferMethod";
// public static final String TRANSFER_MODE_AUTO = "AUTO";
// public static final String TRANSFER_MODE_BINARY = "BINARY";
// public static final String TRANSFER_MODE_ASCII = "ASCII";
// public static final String AUTH_METHOD_USER_PWD = "USER_PWD";
// public static final String AUTH_METHOD_ANONYMOUS = "ANONYMOUS";
// public static final String PARAM_SSL_MODE = "jetbrains.buildServer.deployer.ftp.securityMode";
// public static final String DATA_CHANNEL_PROTECTION = "jetbrains.buildServer.deployer.ftp.dataChannelProtection";
// public static final String PARAM_FTP_MODE = "jetbrains.buildServer.deployer.ftp.ftpMode";
// public static final String PARAM_FTP_CONNECT_TIMEOUT = "jetbrains.deployer.ftp.connectTimeout";
// public static final String PARAM_FTP_CONTROL_KEEP_ALIVE_TIMEOUT = "jetbrains.deployer.ftp.controlKeepAliveTimeout.seconds";
// }
| import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.base.BaseDeployerRunner;
import jetbrains.buildServer.deployer.common.FTPRunnerConstants;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ftp;
public class FtpDeployerRunner extends BaseDeployerRunner {
public FtpDeployerRunner(@NotNull final ExtensionHolder extensionHolder) {
super(extensionHolder);
}
@Override
protected BuildProcess getDeployerProcess(@NotNull final BuildRunnerContext context,
@NotNull final String username,
@NotNull final String password,
@NotNull final String target,
@NotNull final List<ArtifactsCollection> artifactsCollections) throws RunBuildException {
final Map<String, String> runnerParameters = context.getRunnerParameters(); | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/base/BaseDeployerRunner.java
// public abstract class BaseDeployerRunner implements AgentBuildRunner {
// protected final ExtensionHolder myExtensionHolder;
//
// public BaseDeployerRunner(@NotNull final ExtensionHolder extensionHolder) {
// myExtensionHolder = extensionHolder;
// }
//
// @NotNull
// @Override
// public BuildProcess createBuildProcess(@NotNull final AgentRunningBuild runningBuild,
// @NotNull final BuildRunnerContext context) throws RunBuildException {
//
// final Map<String, String> runnerParameters = context.getRunnerParameters();
// final String username = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_USERNAME));
// final String password = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_PASSWORD));
// final String target = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_TARGET_URL));
// final String sourcePaths = runnerParameters.get(DeployerRunnerConstants.PARAM_SOURCE_PATH);
//
// final Collection<ArtifactsPreprocessor> preprocessors = myExtensionHolder.getExtensions(ArtifactsPreprocessor.class);
//
// final ArtifactsBuilder builder = new ArtifactsBuilder();
// builder.setPreprocessors(preprocessors);
// builder.setBaseDir(runningBuild.getCheckoutDirectory());
// builder.setArtifactsPaths(sourcePaths);
//
// final List<ArtifactsCollection> artifactsCollections = builder.build();
//
// return getDeployerProcess(context, username, password, target, artifactsCollections);
// }
//
// protected abstract BuildProcess getDeployerProcess(@NotNull final BuildRunnerContext context,
// @NotNull final String username,
// @NotNull final String password,
// @NotNull final String target,
// @NotNull final List<ArtifactsCollection> artifactsCollections) throws RunBuildException;
//
// @NotNull
// @Override
// public abstract AgentBuildRunnerInfo getRunnerInfo();
// }
//
// Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/FTPRunnerConstants.java
// public class FTPRunnerConstants {
// public static final String PARAM_AUTH_METHOD = "jetbrains.buildServer.deployer.ftp.authMethod";
// public static final String PARAM_TRANSFER_MODE = "jetbrains.buildServer.deployer.ftp.transferMethod";
// public static final String TRANSFER_MODE_AUTO = "AUTO";
// public static final String TRANSFER_MODE_BINARY = "BINARY";
// public static final String TRANSFER_MODE_ASCII = "ASCII";
// public static final String AUTH_METHOD_USER_PWD = "USER_PWD";
// public static final String AUTH_METHOD_ANONYMOUS = "ANONYMOUS";
// public static final String PARAM_SSL_MODE = "jetbrains.buildServer.deployer.ftp.securityMode";
// public static final String DATA_CHANNEL_PROTECTION = "jetbrains.buildServer.deployer.ftp.dataChannelProtection";
// public static final String PARAM_FTP_MODE = "jetbrains.buildServer.deployer.ftp.ftpMode";
// public static final String PARAM_FTP_CONNECT_TIMEOUT = "jetbrains.deployer.ftp.connectTimeout";
// public static final String PARAM_FTP_CONTROL_KEEP_ALIVE_TIMEOUT = "jetbrains.deployer.ftp.controlKeepAliveTimeout.seconds";
// }
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/ftp/FtpDeployerRunner.java
import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.base.BaseDeployerRunner;
import jetbrains.buildServer.deployer.common.FTPRunnerConstants;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ftp;
public class FtpDeployerRunner extends BaseDeployerRunner {
public FtpDeployerRunner(@NotNull final ExtensionHolder extensionHolder) {
super(extensionHolder);
}
@Override
protected BuildProcess getDeployerProcess(@NotNull final BuildRunnerContext context,
@NotNull final String username,
@NotNull final String password,
@NotNull final String target,
@NotNull final List<ArtifactsCollection> artifactsCollections) throws RunBuildException {
final Map<String, String> runnerParameters = context.getRunnerParameters(); | final String authMethod = runnerParameters.get(FTPRunnerConstants.PARAM_AUTH_METHOD); |
JetBrains/teamcity-deployer-plugin | deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SmbDeployerRunType.java | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
| import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.serverSide.RunType;
import jetbrains.buildServer.serverSide.RunTypeRegistry;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
public class SmbDeployerRunType extends RunType {
final private Pattern SIMPLE_UNC_REGEX = Pattern.compile("^(?:(\\\\\\\\)?%[^\\\\%\\s]+%)|(?:\\\\\\\\[^\\\\]+\\\\[^\\\\]+(\\\\[^\\\\]+)*)$");
private final PluginDescriptor myDescriptor;
public SmbDeployerRunType(@NotNull final RunTypeRegistry registry,
@NotNull final PluginDescriptor descriptor) {
registry.registerRunType(this);
myDescriptor = descriptor;
}
@NotNull
@Override
public String getType() { | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
// Path: deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/SmbDeployerRunType.java
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.serverSide.RunType;
import jetbrains.buildServer.serverSide.RunTypeRegistry;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.server;
public class SmbDeployerRunType extends RunType {
final private Pattern SIMPLE_UNC_REGEX = Pattern.compile("^(?:(\\\\\\\\)?%[^\\\\%\\s]+%)|(?:\\\\\\\\[^\\\\]+\\\\[^\\\\]+(\\\\[^\\\\]+)*)$");
private final PluginDescriptor myDescriptor;
public SmbDeployerRunType(@NotNull final RunTypeRegistry registry,
@NotNull final PluginDescriptor descriptor) {
registry.registerRunType(this);
myDescriptor = descriptor;
}
@NotNull
@Override
public String getType() { | return DeployerRunnerConstants.SMB_RUN_TYPE; |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/ssh/SSHDeployerRunnerInfo.java | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
| import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ssh;
/**
* Created by Kit
* Date: 24.03.12 - 17:31
*/
class SSHDeployerRunnerInfo implements AgentBuildRunnerInfo {
@NotNull
@Override
public String getType() { | // Path: deploy-runner-common/src/main/java/jetbrains/buildServer/deployer/common/DeployerRunnerConstants.java
// public class DeployerRunnerConstants {
// public static final String SSH_RUN_TYPE = "ssh-deploy-runner";
// public static final String SMB_RUN_TYPE = "smb-deploy-runner";
// public static final String SMB2_RUN_TYPE = "smb2-deploy-runner";
// public static final String FTP_RUN_TYPE = "ftp-deploy-runner";
// public static final String TOMCAT_RUN_TYPE = "tomcat-deploy-runner";
// public static final String CARGO_RUN_TYPE = "cargo-deploy-runner";
//
//
// public static final String PARAM_USERNAME = "jetbrains.buildServer.deployer.username";
// public static final String PARAM_PASSWORD = "secure:jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_PLAIN_PASSWORD = "jetbrains.buildServer.deployer.password";
// @Deprecated
// public static final String PARAM_DOMAIN = "jetbrains.buildServer.deployer.domain";
// public static final String PARAM_TARGET_URL = "jetbrains.buildServer.deployer.targetUrl";
// public static final String PARAM_SOURCE_PATH = "jetbrains.buildServer.deployer.sourcePath";
// public static final String PARAM_CONTAINER_CONTEXT_PATH = "jetbrains.buildServer.deployer.container.contextPath";
// public static final String PARAM_CONTAINER_TYPE = "jetbrains.buildServer.deployer.container.type";
//
// public static final String BUILD_PROBLEM_TYPE = "jetbrains.buildServer.deployer";
// }
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/ssh/SSHDeployerRunnerInfo.java
import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.deployer.agent.ssh;
/**
* Created by Kit
* Date: 24.03.12 - 17:31
*/
class SSHDeployerRunnerInfo implements AgentBuildRunnerInfo {
@NotNull
@Override
public String getType() { | return DeployerRunnerConstants.SSH_RUN_TYPE; |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent-smb2/src/main/java/jetbrains/buildServer/deployer/agent/smb/SMBJBuildProcessAdapter.java | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/SyncBuildProcessAdapter.java
// public abstract class SyncBuildProcessAdapter extends BuildProcessAdapter {
// protected final BuildProgressLogger myLogger;
// private volatile boolean hasFinished;
// private volatile BuildFinishedStatus statusCode;
// private volatile boolean isInterrupted;
//
//
// public SyncBuildProcessAdapter(@NotNull final BuildProgressLogger logger) {
// myLogger = logger;
// hasFinished = false;
// statusCode = null;
// }
//
//
// @Override
// public void interrupt() {
// isInterrupted = true;
// }
//
// @Override
// public boolean isInterrupted() {
// return isInterrupted;
// }
//
// @Override
// public boolean isFinished() {
// return hasFinished;
// }
//
// @NotNull
// @Override
// public BuildFinishedStatus waitFor() throws RunBuildException {
// while (!isInterrupted() && !hasFinished) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// throw new RunBuildException(e);
// }
// }
// return hasFinished ? statusCode : BuildFinishedStatus.INTERRUPTED;
// }
//
// @Override
// public void start() throws RunBuildException {
// try {
// statusCode = runProcess();
// hasFinished = true;
// } catch (UploadInterruptedException e) {
// hasFinished = false;
// }
// }
//
// /**
// * @return true is process finished successfully
// */
// protected abstract BuildFinishedStatus runProcess();
//
// protected void checkIsInterrupted() throws UploadInterruptedException {
// if (isInterrupted()) throw new UploadInterruptedException();
// }
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/UploadInterruptedException.java
// public class UploadInterruptedException extends RuntimeException {
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/DeployerAgentUtils.java
// public static void logBuildProblem(BuildProgressLogger logger, String message) {
// logger.logBuildProblem(BuildProblemData
// .createBuildProblem(String.valueOf(message.hashCode()),
// DeployerRunnerConstants.BUILD_PROBLEM_TYPE,
// "Deployment problem: " + message));
// }
| import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb.SMB1NotSupportedException;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.common.SMBRuntimeException;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.Share;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.SyncBuildProcessAdapter;
import jetbrains.buildServer.deployer.agent.UploadInterruptedException;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import static com.hierynomus.mssmb2.SMB2CreateDisposition.FILE_OVERWRITE_IF;
import static jetbrains.buildServer.deployer.agent.DeployerAgentUtils.logBuildProblem; | "target=[" + target + "]";
Loggers.AGENT.debug(settingsString);
myLogger.message("Starting upload via SMBj to " + myTarget);
final List<String> components = StringUtil.split(target, "\\");
final String host = components.remove(0);
final String shareName = components.size() > 0 ? components.remove(0) : "";
final String pathInShare = StringUtil.join(components, "\\");
try {
SmbConfig config = SmbConfig
.builder()
.withMultiProtocolNegotiate(true)
.withSigningRequired(true).build();
SMBClient client = new SMBClient(config);
Connection connection = client.connect(host);
Session session = connection.authenticate(new AuthenticationContext(myUsername, myPassword.toCharArray(), myDomain));
Share share = session.connectShare(shareName);
if (share instanceof DiskShare) {
DiskShare diskShare = (DiskShare)share;
for (ArtifactsCollection artifactsCollection : myArtifactsCollections) {
final int numOfUploadedFiles = upload(artifactsCollection.getFilePathMap(), diskShare, pathInShare);
myLogger.message("Uploaded [" + numOfUploadedFiles + "] files for [" + artifactsCollection.getSourcePath() + "] pattern");
}
} else { | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/SyncBuildProcessAdapter.java
// public abstract class SyncBuildProcessAdapter extends BuildProcessAdapter {
// protected final BuildProgressLogger myLogger;
// private volatile boolean hasFinished;
// private volatile BuildFinishedStatus statusCode;
// private volatile boolean isInterrupted;
//
//
// public SyncBuildProcessAdapter(@NotNull final BuildProgressLogger logger) {
// myLogger = logger;
// hasFinished = false;
// statusCode = null;
// }
//
//
// @Override
// public void interrupt() {
// isInterrupted = true;
// }
//
// @Override
// public boolean isInterrupted() {
// return isInterrupted;
// }
//
// @Override
// public boolean isFinished() {
// return hasFinished;
// }
//
// @NotNull
// @Override
// public BuildFinishedStatus waitFor() throws RunBuildException {
// while (!isInterrupted() && !hasFinished) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// throw new RunBuildException(e);
// }
// }
// return hasFinished ? statusCode : BuildFinishedStatus.INTERRUPTED;
// }
//
// @Override
// public void start() throws RunBuildException {
// try {
// statusCode = runProcess();
// hasFinished = true;
// } catch (UploadInterruptedException e) {
// hasFinished = false;
// }
// }
//
// /**
// * @return true is process finished successfully
// */
// protected abstract BuildFinishedStatus runProcess();
//
// protected void checkIsInterrupted() throws UploadInterruptedException {
// if (isInterrupted()) throw new UploadInterruptedException();
// }
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/UploadInterruptedException.java
// public class UploadInterruptedException extends RuntimeException {
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/DeployerAgentUtils.java
// public static void logBuildProblem(BuildProgressLogger logger, String message) {
// logger.logBuildProblem(BuildProblemData
// .createBuildProblem(String.valueOf(message.hashCode()),
// DeployerRunnerConstants.BUILD_PROBLEM_TYPE,
// "Deployment problem: " + message));
// }
// Path: deploy-runner-agent-smb2/src/main/java/jetbrains/buildServer/deployer/agent/smb/SMBJBuildProcessAdapter.java
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb.SMB1NotSupportedException;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.common.SMBRuntimeException;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.Share;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.SyncBuildProcessAdapter;
import jetbrains.buildServer.deployer.agent.UploadInterruptedException;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import static com.hierynomus.mssmb2.SMB2CreateDisposition.FILE_OVERWRITE_IF;
import static jetbrains.buildServer.deployer.agent.DeployerAgentUtils.logBuildProblem;
"target=[" + target + "]";
Loggers.AGENT.debug(settingsString);
myLogger.message("Starting upload via SMBj to " + myTarget);
final List<String> components = StringUtil.split(target, "\\");
final String host = components.remove(0);
final String shareName = components.size() > 0 ? components.remove(0) : "";
final String pathInShare = StringUtil.join(components, "\\");
try {
SmbConfig config = SmbConfig
.builder()
.withMultiProtocolNegotiate(true)
.withSigningRequired(true).build();
SMBClient client = new SMBClient(config);
Connection connection = client.connect(host);
Session session = connection.authenticate(new AuthenticationContext(myUsername, myPassword.toCharArray(), myDomain));
Share share = session.connectShare(shareName);
if (share instanceof DiskShare) {
DiskShare diskShare = (DiskShare)share;
for (ArtifactsCollection artifactsCollection : myArtifactsCollections) {
final int numOfUploadedFiles = upload(artifactsCollection.getFilePathMap(), diskShare, pathInShare);
myLogger.message("Uploaded [" + numOfUploadedFiles + "] files for [" + artifactsCollection.getSourcePath() + "] pattern");
}
} else { | logBuildProblem(myLogger, "Shared resource [" + shareName + "] is not a folder, can not upload files."); |
JetBrains/teamcity-deployer-plugin | deploy-runner-agent-smb2/src/main/java/jetbrains/buildServer/deployer/agent/smb/SMBJBuildProcessAdapter.java | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/SyncBuildProcessAdapter.java
// public abstract class SyncBuildProcessAdapter extends BuildProcessAdapter {
// protected final BuildProgressLogger myLogger;
// private volatile boolean hasFinished;
// private volatile BuildFinishedStatus statusCode;
// private volatile boolean isInterrupted;
//
//
// public SyncBuildProcessAdapter(@NotNull final BuildProgressLogger logger) {
// myLogger = logger;
// hasFinished = false;
// statusCode = null;
// }
//
//
// @Override
// public void interrupt() {
// isInterrupted = true;
// }
//
// @Override
// public boolean isInterrupted() {
// return isInterrupted;
// }
//
// @Override
// public boolean isFinished() {
// return hasFinished;
// }
//
// @NotNull
// @Override
// public BuildFinishedStatus waitFor() throws RunBuildException {
// while (!isInterrupted() && !hasFinished) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// throw new RunBuildException(e);
// }
// }
// return hasFinished ? statusCode : BuildFinishedStatus.INTERRUPTED;
// }
//
// @Override
// public void start() throws RunBuildException {
// try {
// statusCode = runProcess();
// hasFinished = true;
// } catch (UploadInterruptedException e) {
// hasFinished = false;
// }
// }
//
// /**
// * @return true is process finished successfully
// */
// protected abstract BuildFinishedStatus runProcess();
//
// protected void checkIsInterrupted() throws UploadInterruptedException {
// if (isInterrupted()) throw new UploadInterruptedException();
// }
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/UploadInterruptedException.java
// public class UploadInterruptedException extends RuntimeException {
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/DeployerAgentUtils.java
// public static void logBuildProblem(BuildProgressLogger logger, String message) {
// logger.logBuildProblem(BuildProblemData
// .createBuildProblem(String.valueOf(message.hashCode()),
// DeployerRunnerConstants.BUILD_PROBLEM_TYPE,
// "Deployment problem: " + message));
// }
| import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb.SMB1NotSupportedException;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.common.SMBRuntimeException;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.Share;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.SyncBuildProcessAdapter;
import jetbrains.buildServer.deployer.agent.UploadInterruptedException;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import static com.hierynomus.mssmb2.SMB2CreateDisposition.FILE_OVERWRITE_IF;
import static jetbrains.buildServer.deployer.agent.DeployerAgentUtils.logBuildProblem; |
Connection connection = client.connect(host);
Session session = connection.authenticate(new AuthenticationContext(myUsername, myPassword.toCharArray(), myDomain));
Share share = session.connectShare(shareName);
if (share instanceof DiskShare) {
DiskShare diskShare = (DiskShare)share;
for (ArtifactsCollection artifactsCollection : myArtifactsCollections) {
final int numOfUploadedFiles = upload(artifactsCollection.getFilePathMap(), diskShare, pathInShare);
myLogger.message("Uploaded [" + numOfUploadedFiles + "] files for [" + artifactsCollection.getSourcePath() + "] pattern");
}
} else {
logBuildProblem(myLogger, "Shared resource [" + shareName + "] is not a folder, can not upload files.");
return BuildFinishedStatus.FINISHED_FAILED;
}
return BuildFinishedStatus.FINISHED_SUCCESS;
} catch (TransportException e) {
final String message;
if (hasCauseOfType(SMB1NotSupportedException.class, e)) {
message = "The remote host [" + host + "] does not support SMBv2 or support was explicitly disabled. Please, check the remote host configuration";
} else {
message = e.getMessage();
}
logBuildProblem(myLogger, message);
LOG.warnAndDebugDetails("Error executing SMB command", e);
return BuildFinishedStatus.FINISHED_FAILED; | // Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/SyncBuildProcessAdapter.java
// public abstract class SyncBuildProcessAdapter extends BuildProcessAdapter {
// protected final BuildProgressLogger myLogger;
// private volatile boolean hasFinished;
// private volatile BuildFinishedStatus statusCode;
// private volatile boolean isInterrupted;
//
//
// public SyncBuildProcessAdapter(@NotNull final BuildProgressLogger logger) {
// myLogger = logger;
// hasFinished = false;
// statusCode = null;
// }
//
//
// @Override
// public void interrupt() {
// isInterrupted = true;
// }
//
// @Override
// public boolean isInterrupted() {
// return isInterrupted;
// }
//
// @Override
// public boolean isFinished() {
// return hasFinished;
// }
//
// @NotNull
// @Override
// public BuildFinishedStatus waitFor() throws RunBuildException {
// while (!isInterrupted() && !hasFinished) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// throw new RunBuildException(e);
// }
// }
// return hasFinished ? statusCode : BuildFinishedStatus.INTERRUPTED;
// }
//
// @Override
// public void start() throws RunBuildException {
// try {
// statusCode = runProcess();
// hasFinished = true;
// } catch (UploadInterruptedException e) {
// hasFinished = false;
// }
// }
//
// /**
// * @return true is process finished successfully
// */
// protected abstract BuildFinishedStatus runProcess();
//
// protected void checkIsInterrupted() throws UploadInterruptedException {
// if (isInterrupted()) throw new UploadInterruptedException();
// }
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/UploadInterruptedException.java
// public class UploadInterruptedException extends RuntimeException {
//
// }
//
// Path: deploy-runner-agent/src/main/java/jetbrains/buildServer/deployer/agent/DeployerAgentUtils.java
// public static void logBuildProblem(BuildProgressLogger logger, String message) {
// logger.logBuildProblem(BuildProblemData
// .createBuildProblem(String.valueOf(message.hashCode()),
// DeployerRunnerConstants.BUILD_PROBLEM_TYPE,
// "Deployment problem: " + message));
// }
// Path: deploy-runner-agent-smb2/src/main/java/jetbrains/buildServer/deployer/agent/smb/SMBJBuildProcessAdapter.java
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb.SMB1NotSupportedException;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.common.SMBRuntimeException;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.Share;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection;
import jetbrains.buildServer.deployer.agent.SyncBuildProcessAdapter;
import jetbrains.buildServer.deployer.agent.UploadInterruptedException;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import static com.hierynomus.mssmb2.SMB2CreateDisposition.FILE_OVERWRITE_IF;
import static jetbrains.buildServer.deployer.agent.DeployerAgentUtils.logBuildProblem;
Connection connection = client.connect(host);
Session session = connection.authenticate(new AuthenticationContext(myUsername, myPassword.toCharArray(), myDomain));
Share share = session.connectShare(shareName);
if (share instanceof DiskShare) {
DiskShare diskShare = (DiskShare)share;
for (ArtifactsCollection artifactsCollection : myArtifactsCollections) {
final int numOfUploadedFiles = upload(artifactsCollection.getFilePathMap(), diskShare, pathInShare);
myLogger.message("Uploaded [" + numOfUploadedFiles + "] files for [" + artifactsCollection.getSourcePath() + "] pattern");
}
} else {
logBuildProblem(myLogger, "Shared resource [" + shareName + "] is not a folder, can not upload files.");
return BuildFinishedStatus.FINISHED_FAILED;
}
return BuildFinishedStatus.FINISHED_SUCCESS;
} catch (TransportException e) {
final String message;
if (hasCauseOfType(SMB1NotSupportedException.class, e)) {
message = "The remote host [" + host + "] does not support SMBv2 or support was explicitly disabled. Please, check the remote host configuration";
} else {
message = e.getMessage();
}
logBuildProblem(myLogger, message);
LOG.warnAndDebugDetails("Error executing SMB command", e);
return BuildFinishedStatus.FINISHED_FAILED; | } catch (UploadInterruptedException e) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.