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 |
|---|---|---|---|---|---|---|
nkarasch/ChessGDX | core/src/nkarasch/chessgdx/util/GraphicsSettings.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
| import java.util.Iterator;
import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array; | mDisplayModes.sort();
}
/**
* @return a CustomDisplayMode instance representing the starting screen
* width and screen height
*/
public CustomDisplayMode getLaunchDisplayMode() {
for (CustomDisplayMode m : mDisplayModes) {
if (m.width == Gdx.graphics.getWidth() && m.height == Gdx.graphics.getHeight()) {
return m;
}
}
return mDisplayModes.get(0);
}
/**
* @return all available display modes that aren't using lower refresh rates
* or color depth
*/
public Array<CustomDisplayMode> getDisplayModes() {
return mDisplayModes;
}
/**
* Sets the window display mode to match the options set in preferences in
* preferences. This is called at launch.
*/
public static void setGraphics() { | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
// Path: core/src/nkarasch/chessgdx/util/GraphicsSettings.java
import java.util.Iterator;
import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
mDisplayModes.sort();
}
/**
* @return a CustomDisplayMode instance representing the starting screen
* width and screen height
*/
public CustomDisplayMode getLaunchDisplayMode() {
for (CustomDisplayMode m : mDisplayModes) {
if (m.width == Gdx.graphics.getWidth() && m.height == Gdx.graphics.getHeight()) {
return m;
}
}
return mDisplayModes.get(0);
}
/**
* @return all available display modes that aren't using lower refresh rates
* or color depth
*/
public Array<CustomDisplayMode> getDisplayModes() {
return mDisplayModes;
}
/**
* Sets the window display mode to match the options set in preferences in
* preferences. This is called at launch.
*/
public static void setGraphics() { | Preferences pref = Gdx.app.getPreferences(GameCore.TITLE); |
nkarasch/ChessGDX | desktop/src/nkarasch/chessgdx/desktop/DesktopLauncher.java | // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
| import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; | package nkarasch.chessgdx.desktop;
public class DesktopLauncher {
public static void main(String[] arg) {
final LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "ChessGDX";
cfg.width = 1920;
cfg.height = 1080;
cfg.backgroundFPS = 30;
cfg.foregroundFPS = 0;
cfg.vSyncEnabled = false;
cfg.samples = 16;
cfg.resizable = false;
final Runnable rebootable = new Runnable() {
@Override
public void run() {
if (Gdx.app != null) {
Gdx.app.exit();
}
DesktopLauncher.restart(DesktopLauncher.class);
}
};
| // Path: core/src/nkarasch/chessgdx/GameCore.java
// public class GameCore implements ApplicationListener {
//
// public static final String TITLE = "ChessGDX";
//
// private Camera mCameraController;
// private ChessLogicController mLogicController;
// private BoardController mBoardController;
// private PerspectiveRenderer mPerspectiveRenderer;
// private OverlayRenderer mOverlayRenderer;
//
// private static Runnable rebootHook;
//
// /**
// * @param rebootHook
// * game restart hook
// */
// public GameCore(final Runnable rebootHook) {
// GameCore.rebootHook = rebootHook;
// }
//
// @Override
// public void create() {
// GraphicsSettings.setGraphics();
// mCameraController = new Camera();
// mOverlayRenderer = new OverlayRenderer(this);
// mLogicController = new ChessLogicController(mOverlayRenderer);
// mBoardController = new BoardController(mCameraController, mLogicController, mOverlayRenderer);
// mPerspectiveRenderer = new PerspectiveRenderer(mCameraController, mBoardController, mLogicController.getPlacement());
//
// Gdx.input.setInputProcessor(new InputMultiplexer(mOverlayRenderer, mBoardController, mCameraController.getOrbitController()));
// }
//
// @Override
// public void render() {
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// mCameraController.update();
// mPerspectiveRenderer.render();
// mOverlayRenderer.render();
// }
//
// @Override
// public void resize(int width, int height) {
// // requiring restart on resize instead, this would be tedious to set up
// }
//
// @Override
// public void pause() {
// // not supporting mobile
// }
//
// @Override
// public void resume() {
// // not supporting mobile
// }
//
// @Override
// public void dispose() {
// AssetHandler.getInstance().dispose();
// mLogicController.dispose();
// mOverlayRenderer.dispose();
// }
//
// /**
// * Restarts game client
// */
// public static void restart() {
// Gdx.app.postRunnable(GameCore.rebootHook);
// }
//
// /**
// * Restores board back to the new game state
// *
// * @param isWhite
// * player color
// */
// public void newGame(boolean isWhite) {
// mBoardController.setPlayerColor(isWhite);
// mBoardController.resetList();
// mLogicController.resetPosition();
// mOverlayRenderer.getCheckmateDialog().setState(false, false);
// mOverlayRenderer.getMoveHistory().resetHistory();
// }
// }
// Path: desktop/src/nkarasch/chessgdx/desktop/DesktopLauncher.java
import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import nkarasch.chessgdx.GameCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
package nkarasch.chessgdx.desktop;
public class DesktopLauncher {
public static void main(String[] arg) {
final LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "ChessGDX";
cfg.width = 1920;
cfg.height = 1080;
cfg.backgroundFPS = 30;
cfg.foregroundFPS = 0;
cfg.vSyncEnabled = false;
cfg.samples = 16;
cfg.resizable = false;
final Runnable rebootable = new Runnable() {
@Override
public void run() {
if (Gdx.app != null) {
Gdx.app.exit();
}
DesktopLauncher.restart(DesktopLauncher.class);
}
};
| new LwjglApplication(new GameCore(rebootable), cfg); |
norbertmartin12/site-monitor | app/src/main/java/org/site_monitor/service/SharedPreferencesService.java | // Path: app/src/main/java/org/site_monitor/util/GsonUtil.java
// public class GsonUtil {
//
// public static String toJson(Object obj) {
// return getGson().toJson(obj);
// }
//
// public static <T> T fromJson(String json, Class<T> objClass) {
// return objClass.cast(getGson().fromJson(json, objClass));
// }
//
// public static <T> T fromJson(String json, TypeToken<T> typeToken) {
// return getGson().fromJson(json, typeToken.getType());
// }
//
// private static Gson getGson() {
// return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
// }
// }
| import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.util.GsonUtil;
import java.io.Serializable; | * @param key
* @param value
*/
public static void saveNow(Context context, String key, String value) {
SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
defaultSharedPreferences.edit().putString(key, value).commit();
}
/**
* Saves value for given key in default shard preferences.
*
* @param context
* @param key
* @param value
*/
public static void saveNow(Context context, String key, long value) {
SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
defaultSharedPreferences.edit().putLong(key, value).commit();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_SAVE_DATA.equals(action)) {
final String key = intent.getStringExtra(EXTRA_DATA_KEY);
final Serializable data = intent.getSerializableExtra(EXTRA_DATA);
if (BuildConfig.DEBUG) {
Log.d(TAG, "handleActionSaveData key: " + key);
} | // Path: app/src/main/java/org/site_monitor/util/GsonUtil.java
// public class GsonUtil {
//
// public static String toJson(Object obj) {
// return getGson().toJson(obj);
// }
//
// public static <T> T fromJson(String json, Class<T> objClass) {
// return objClass.cast(getGson().fromJson(json, objClass));
// }
//
// public static <T> T fromJson(String json, TypeToken<T> typeToken) {
// return getGson().fromJson(json, typeToken.getType());
// }
//
// private static Gson getGson() {
// return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
// }
// }
// Path: app/src/main/java/org/site_monitor/service/SharedPreferencesService.java
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.util.GsonUtil;
import java.io.Serializable;
* @param key
* @param value
*/
public static void saveNow(Context context, String key, String value) {
SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
defaultSharedPreferences.edit().putString(key, value).commit();
}
/**
* Saves value for given key in default shard preferences.
*
* @param context
* @param key
* @param value
*/
public static void saveNow(Context context, String key, long value) {
SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
defaultSharedPreferences.edit().putLong(key, value).commit();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_SAVE_DATA.equals(action)) {
final String key = intent.getStringExtra(EXTRA_DATA_KEY);
final Serializable data = intent.getSerializableExtra(EXTRA_DATA);
if (BuildConfig.DEBUG) {
Log.d(TAG, "handleActionSaveData key: " + key);
} | saveNow(this, key, GsonUtil.toJson(data)); |
norbertmartin12/site-monitor | app/src/main/java/org/site_monitor/model/db/DBSiteSettings.java | // Path: app/src/main/java/org/site_monitor/model/bo/SiteSettings.java
// @DatabaseTable
// public class SiteSettings implements Parcelable {
//
// public static final Creator<SiteSettings> CREATOR = new Creator<SiteSettings>() {
// @Override
// public SiteSettings createFromParcel(Parcel in) {
// return new SiteSettings(in);
// }
//
// @Override
// public SiteSettings[] newArray(int size) {
// return new SiteSettings[size];
// }
// };
//
// @DatabaseField(generatedId = true)
// private Long id;
// @DatabaseField
// private String name;
// @DatabaseField(canBeNull = false, uniqueIndex = true)
// private String host;
// @DatabaseField(canBeNull = true, uniqueIndex = true)
// private String internalUrl;
// @DatabaseField
// private boolean isNotificationEnabled = true;
// @DatabaseField
// private boolean forcedCertificate = false;
// @DatabaseField(dataType = DataType.BYTE_ARRAY)
// private byte[] favicon;
// @ForeignCollectionField(eager = true)
// private ForeignCollection<SiteCall> siteCalls;
//
//
// public SiteSettings() {
// }
//
// public SiteSettings(String host) {
// this.host = host;
// this.name = host;
// }
//
// public SiteSettings(Parcel in) {
// name = in.readString();
// host = in.readString();
// internalUrl = in.readString();
// isNotificationEnabled = in.readInt() == 1;
// in.readByteArray(favicon);
// }
//
// public String getHost() {
// return host;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isNotificationEnabled() {
// return isNotificationEnabled;
// }
//
// public void setNotificationEnabled(boolean notificationEnabled) {
// this.isNotificationEnabled = notificationEnabled;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public ForeignCollection<SiteCall> getSiteCalls() {
// return siteCalls;
// }
//
// public void setSiteCalls(ForeignCollection<SiteCall> siteCalls) {
// this.siteCalls = siteCalls;
// }
//
// public boolean isForcedCertificate() {
// return forcedCertificate;
// }
//
// public void setForcedCertificate(boolean forcedCertificate) {
// this.forcedCertificate = forcedCertificate;
// }
//
// public byte[] getFavicon() {
// return favicon;
// }
//
// public void setFavicon(byte[] favicon) {
// this.favicon = favicon;
// }
//
// public String getInternalUrl() {
// return internalUrl;
// }
//
// public void setInternalUrl(String internalUrl) {
// this.internalUrl = internalUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof SiteSettings) {
// SiteSettings obj = (SiteSettings) o;
// return host.equals(obj.host);
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return host.hashCode();
// }
//
// @Override
// public String toString() {
// return "SiteSettings{" +
// "name='" + name + '\'' +
// ", host='" + host + '\'' +
// ", internalUrl='" + internalUrl + '\'' +
// ", isNotificationEnabled=" + isNotificationEnabled +
// ", calls=" + (siteCalls == null ? "0" : siteCalls.size()) +
// '}';
// }
//
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(name);
// dest.writeString(host);
// dest.writeString(internalUrl);
// dest.writeInt(isNotificationEnabled ? 1 : 0);
// if (favicon != null) {
// dest.writeByteArray(favicon);
// }
// }
//
// }
| import com.j256.ormlite.dao.Dao;
import org.site_monitor.model.bo.SiteSettings;
import java.sql.SQLException;
import java.util.List; | /*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.model.db;
/**
* Created by Martin Norbert on 31/01/2016.
*/
public class DBSiteSettings {
private static final String F_HOST = "host";
| // Path: app/src/main/java/org/site_monitor/model/bo/SiteSettings.java
// @DatabaseTable
// public class SiteSettings implements Parcelable {
//
// public static final Creator<SiteSettings> CREATOR = new Creator<SiteSettings>() {
// @Override
// public SiteSettings createFromParcel(Parcel in) {
// return new SiteSettings(in);
// }
//
// @Override
// public SiteSettings[] newArray(int size) {
// return new SiteSettings[size];
// }
// };
//
// @DatabaseField(generatedId = true)
// private Long id;
// @DatabaseField
// private String name;
// @DatabaseField(canBeNull = false, uniqueIndex = true)
// private String host;
// @DatabaseField(canBeNull = true, uniqueIndex = true)
// private String internalUrl;
// @DatabaseField
// private boolean isNotificationEnabled = true;
// @DatabaseField
// private boolean forcedCertificate = false;
// @DatabaseField(dataType = DataType.BYTE_ARRAY)
// private byte[] favicon;
// @ForeignCollectionField(eager = true)
// private ForeignCollection<SiteCall> siteCalls;
//
//
// public SiteSettings() {
// }
//
// public SiteSettings(String host) {
// this.host = host;
// this.name = host;
// }
//
// public SiteSettings(Parcel in) {
// name = in.readString();
// host = in.readString();
// internalUrl = in.readString();
// isNotificationEnabled = in.readInt() == 1;
// in.readByteArray(favicon);
// }
//
// public String getHost() {
// return host;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isNotificationEnabled() {
// return isNotificationEnabled;
// }
//
// public void setNotificationEnabled(boolean notificationEnabled) {
// this.isNotificationEnabled = notificationEnabled;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public ForeignCollection<SiteCall> getSiteCalls() {
// return siteCalls;
// }
//
// public void setSiteCalls(ForeignCollection<SiteCall> siteCalls) {
// this.siteCalls = siteCalls;
// }
//
// public boolean isForcedCertificate() {
// return forcedCertificate;
// }
//
// public void setForcedCertificate(boolean forcedCertificate) {
// this.forcedCertificate = forcedCertificate;
// }
//
// public byte[] getFavicon() {
// return favicon;
// }
//
// public void setFavicon(byte[] favicon) {
// this.favicon = favicon;
// }
//
// public String getInternalUrl() {
// return internalUrl;
// }
//
// public void setInternalUrl(String internalUrl) {
// this.internalUrl = internalUrl;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof SiteSettings) {
// SiteSettings obj = (SiteSettings) o;
// return host.equals(obj.host);
// }
// return false;
// }
//
// @Override
// public int hashCode() {
// return host.hashCode();
// }
//
// @Override
// public String toString() {
// return "SiteSettings{" +
// "name='" + name + '\'' +
// ", host='" + host + '\'' +
// ", internalUrl='" + internalUrl + '\'' +
// ", isNotificationEnabled=" + isNotificationEnabled +
// ", calls=" + (siteCalls == null ? "0" : siteCalls.size()) +
// '}';
// }
//
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(name);
// dest.writeString(host);
// dest.writeString(internalUrl);
// dest.writeInt(isNotificationEnabled ? 1 : 0);
// if (favicon != null) {
// dest.writeByteArray(favicon);
// }
// }
//
// }
// Path: app/src/main/java/org/site_monitor/model/db/DBSiteSettings.java
import com.j256.ormlite.dao.Dao;
import org.site_monitor.model.bo.SiteSettings;
import java.sql.SQLException;
import java.util.List;
/*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.model.db;
/**
* Created by Martin Norbert on 31/01/2016.
*/
public class DBSiteSettings {
private static final String F_HOST = "host";
| private Dao<SiteSettings, Long> dao; |
norbertmartin12/site-monitor | app/src/main/java/org/site_monitor/service/PurgeDbService.java | // Path: app/src/main/java/org/site_monitor/model/db/DBHelper.java
// public class DBHelper extends OrmLiteSqliteOpenHelper {
//
// private static final String DATABASE_NAME = "sitemonitor.db";
// private static final int DATABASE_VERSION = 2;
// private static final String TAG = DBHelper.class.getSimpleName();
//
// public DBHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * Returns DBHelper. Each time you call this method, you must call #release
// *
// * @param context
// * @return DBHelper
// * @see #release()
// */
// public static DBHelper getHelper(Context context) {
// return OpenHelperManager.getHelper(context, DBHelper.class);
// }
//
// /**
// * This is called when the database is first created. Usually you should call createTable statements here to create
// * the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, SiteSettings.class);
// TableUtils.createTable(connectionSource, SiteCall.class);
// Log.i(DBHelper.class.getName(), "database created");
// } catch (SQLException e) {
// Log.e(TAG, "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// /**
// * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
// * the various data to match the new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// try {
// Dao<SiteSettings, Long> dao = getDao(SiteSettings.class);
// dao.executeRaw("ALTER TABLE `sitesettings` ADD COLUMN internalUrl VARCHAR;");
// } catch (SQLException e) {
// Log.e(TAG, "onUpgrade < 2, oldVersion: " + oldVersion + " newVersion: " + newVersion, e);
// }
// }
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// }
//
// public DBSiteSettings getDBSiteSettings() throws SQLException {
// return new DBSiteSettings(this.<Dao<SiteSettings, Long>, SiteSettings>getDao(SiteSettings.class));
// }
//
// public DBSiteCall getDBSiteCall() throws SQLException {
// return new DBSiteCall(this.<Dao<SiteCall, Long>, SiteCall>getDao(SiteCall.class));
// }
//
//
// /**
// * Must be call by each entities that has call #getHelper before when no more using it.
// */
// public void release() {
// OpenHelperManager.releaseHelper();
// }
// }
//
// Path: app/src/main/java/org/site_monitor/model/db/DBSiteCall.java
// public class DBSiteCall {
//
// private Dao<SiteCall, Long> dao;
//
// public DBSiteCall(Dao<SiteCall, Long> dao) {
// this.dao = dao;
// }
//
// public int create(SiteCall siteCall) throws SQLException {
// return dao.create(siteCall);
// }
//
// public int removeCallsBefore(Date date) throws SQLException {
// return dao.delete((PreparedDelete<SiteCall>) dao.deleteBuilder().where().lt("date", date).prepare());
// }
// }
| import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.model.db.DBHelper;
import org.site_monitor.model.db.DBSiteCall;
import java.sql.SQLException;
import java.util.Calendar; | /*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.service;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*/
public class PurgeDbService extends JobIntentService {
private static final String ACTION_PURGE_CALLS = "org.site_monitor.service.action.PURGE_CALLS";
private static final String TAG = PurgeDbService.class.getSimpleName();
public static Intent intent(Context context) {
return new Intent(context, PurgeDbService.class).setAction(ACTION_PURGE_CALLS);
}
/**
* Called serially for each work dispatched to and processed by the service. This
* method is called on a background thread, so you can do long blocking operations
* here. Upon returning, that work will be considered complete and either the next
* pending work dispatched here or the overall service destroyed now that it has
* nothing else to do.
* <p>
* <p>Be aware that when running as a job, you are limited by the maximum job execution
* time and any single or total sequential items of work that exceeds that limit will
* cause the service to be stopped while in progress and later restarted with the
* last unfinished work. (There is currently no limit on execution duration when
* running as a pre-O plain Service.)</p>
*
* @param intent The intent describing the work to now be processed.
*/
@Override
protected void onHandleWork(@NonNull Intent intent) {
final String action = intent.getAction();
if (action == null) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "onHandleIntent: no action");
}
return;
}
if (ACTION_PURGE_CALLS.equals(action)) {
purgeCalls();
}
}
private void purgeCalls() {
try { | // Path: app/src/main/java/org/site_monitor/model/db/DBHelper.java
// public class DBHelper extends OrmLiteSqliteOpenHelper {
//
// private static final String DATABASE_NAME = "sitemonitor.db";
// private static final int DATABASE_VERSION = 2;
// private static final String TAG = DBHelper.class.getSimpleName();
//
// public DBHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * Returns DBHelper. Each time you call this method, you must call #release
// *
// * @param context
// * @return DBHelper
// * @see #release()
// */
// public static DBHelper getHelper(Context context) {
// return OpenHelperManager.getHelper(context, DBHelper.class);
// }
//
// /**
// * This is called when the database is first created. Usually you should call createTable statements here to create
// * the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, SiteSettings.class);
// TableUtils.createTable(connectionSource, SiteCall.class);
// Log.i(DBHelper.class.getName(), "database created");
// } catch (SQLException e) {
// Log.e(TAG, "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// /**
// * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
// * the various data to match the new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// try {
// Dao<SiteSettings, Long> dao = getDao(SiteSettings.class);
// dao.executeRaw("ALTER TABLE `sitesettings` ADD COLUMN internalUrl VARCHAR;");
// } catch (SQLException e) {
// Log.e(TAG, "onUpgrade < 2, oldVersion: " + oldVersion + " newVersion: " + newVersion, e);
// }
// }
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// }
//
// public DBSiteSettings getDBSiteSettings() throws SQLException {
// return new DBSiteSettings(this.<Dao<SiteSettings, Long>, SiteSettings>getDao(SiteSettings.class));
// }
//
// public DBSiteCall getDBSiteCall() throws SQLException {
// return new DBSiteCall(this.<Dao<SiteCall, Long>, SiteCall>getDao(SiteCall.class));
// }
//
//
// /**
// * Must be call by each entities that has call #getHelper before when no more using it.
// */
// public void release() {
// OpenHelperManager.releaseHelper();
// }
// }
//
// Path: app/src/main/java/org/site_monitor/model/db/DBSiteCall.java
// public class DBSiteCall {
//
// private Dao<SiteCall, Long> dao;
//
// public DBSiteCall(Dao<SiteCall, Long> dao) {
// this.dao = dao;
// }
//
// public int create(SiteCall siteCall) throws SQLException {
// return dao.create(siteCall);
// }
//
// public int removeCallsBefore(Date date) throws SQLException {
// return dao.delete((PreparedDelete<SiteCall>) dao.deleteBuilder().where().lt("date", date).prepare());
// }
// }
// Path: app/src/main/java/org/site_monitor/service/PurgeDbService.java
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.model.db.DBHelper;
import org.site_monitor.model.db.DBSiteCall;
import java.sql.SQLException;
import java.util.Calendar;
/*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.service;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*/
public class PurgeDbService extends JobIntentService {
private static final String ACTION_PURGE_CALLS = "org.site_monitor.service.action.PURGE_CALLS";
private static final String TAG = PurgeDbService.class.getSimpleName();
public static Intent intent(Context context) {
return new Intent(context, PurgeDbService.class).setAction(ACTION_PURGE_CALLS);
}
/**
* Called serially for each work dispatched to and processed by the service. This
* method is called on a background thread, so you can do long blocking operations
* here. Upon returning, that work will be considered complete and either the next
* pending work dispatched here or the overall service destroyed now that it has
* nothing else to do.
* <p>
* <p>Be aware that when running as a job, you are limited by the maximum job execution
* time and any single or total sequential items of work that exceeds that limit will
* cause the service to be stopped while in progress and later restarted with the
* last unfinished work. (There is currently no limit on execution duration when
* running as a pre-O plain Service.)</p>
*
* @param intent The intent describing the work to now be processed.
*/
@Override
protected void onHandleWork(@NonNull Intent intent) {
final String action = intent.getAction();
if (action == null) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "onHandleIntent: no action");
}
return;
}
if (ACTION_PURGE_CALLS.equals(action)) {
purgeCalls();
}
}
private void purgeCalls() {
try { | DBHelper dbHelper = DBHelper.getHelper(this); |
norbertmartin12/site-monitor | app/src/main/java/org/site_monitor/service/PurgeDbService.java | // Path: app/src/main/java/org/site_monitor/model/db/DBHelper.java
// public class DBHelper extends OrmLiteSqliteOpenHelper {
//
// private static final String DATABASE_NAME = "sitemonitor.db";
// private static final int DATABASE_VERSION = 2;
// private static final String TAG = DBHelper.class.getSimpleName();
//
// public DBHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * Returns DBHelper. Each time you call this method, you must call #release
// *
// * @param context
// * @return DBHelper
// * @see #release()
// */
// public static DBHelper getHelper(Context context) {
// return OpenHelperManager.getHelper(context, DBHelper.class);
// }
//
// /**
// * This is called when the database is first created. Usually you should call createTable statements here to create
// * the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, SiteSettings.class);
// TableUtils.createTable(connectionSource, SiteCall.class);
// Log.i(DBHelper.class.getName(), "database created");
// } catch (SQLException e) {
// Log.e(TAG, "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// /**
// * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
// * the various data to match the new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// try {
// Dao<SiteSettings, Long> dao = getDao(SiteSettings.class);
// dao.executeRaw("ALTER TABLE `sitesettings` ADD COLUMN internalUrl VARCHAR;");
// } catch (SQLException e) {
// Log.e(TAG, "onUpgrade < 2, oldVersion: " + oldVersion + " newVersion: " + newVersion, e);
// }
// }
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// }
//
// public DBSiteSettings getDBSiteSettings() throws SQLException {
// return new DBSiteSettings(this.<Dao<SiteSettings, Long>, SiteSettings>getDao(SiteSettings.class));
// }
//
// public DBSiteCall getDBSiteCall() throws SQLException {
// return new DBSiteCall(this.<Dao<SiteCall, Long>, SiteCall>getDao(SiteCall.class));
// }
//
//
// /**
// * Must be call by each entities that has call #getHelper before when no more using it.
// */
// public void release() {
// OpenHelperManager.releaseHelper();
// }
// }
//
// Path: app/src/main/java/org/site_monitor/model/db/DBSiteCall.java
// public class DBSiteCall {
//
// private Dao<SiteCall, Long> dao;
//
// public DBSiteCall(Dao<SiteCall, Long> dao) {
// this.dao = dao;
// }
//
// public int create(SiteCall siteCall) throws SQLException {
// return dao.create(siteCall);
// }
//
// public int removeCallsBefore(Date date) throws SQLException {
// return dao.delete((PreparedDelete<SiteCall>) dao.deleteBuilder().where().lt("date", date).prepare());
// }
// }
| import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.model.db.DBHelper;
import org.site_monitor.model.db.DBSiteCall;
import java.sql.SQLException;
import java.util.Calendar; | /*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.service;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*/
public class PurgeDbService extends JobIntentService {
private static final String ACTION_PURGE_CALLS = "org.site_monitor.service.action.PURGE_CALLS";
private static final String TAG = PurgeDbService.class.getSimpleName();
public static Intent intent(Context context) {
return new Intent(context, PurgeDbService.class).setAction(ACTION_PURGE_CALLS);
}
/**
* Called serially for each work dispatched to and processed by the service. This
* method is called on a background thread, so you can do long blocking operations
* here. Upon returning, that work will be considered complete and either the next
* pending work dispatched here or the overall service destroyed now that it has
* nothing else to do.
* <p>
* <p>Be aware that when running as a job, you are limited by the maximum job execution
* time and any single or total sequential items of work that exceeds that limit will
* cause the service to be stopped while in progress and later restarted with the
* last unfinished work. (There is currently no limit on execution duration when
* running as a pre-O plain Service.)</p>
*
* @param intent The intent describing the work to now be processed.
*/
@Override
protected void onHandleWork(@NonNull Intent intent) {
final String action = intent.getAction();
if (action == null) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "onHandleIntent: no action");
}
return;
}
if (ACTION_PURGE_CALLS.equals(action)) {
purgeCalls();
}
}
private void purgeCalls() {
try {
DBHelper dbHelper = DBHelper.getHelper(this); | // Path: app/src/main/java/org/site_monitor/model/db/DBHelper.java
// public class DBHelper extends OrmLiteSqliteOpenHelper {
//
// private static final String DATABASE_NAME = "sitemonitor.db";
// private static final int DATABASE_VERSION = 2;
// private static final String TAG = DBHelper.class.getSimpleName();
//
// public DBHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * Returns DBHelper. Each time you call this method, you must call #release
// *
// * @param context
// * @return DBHelper
// * @see #release()
// */
// public static DBHelper getHelper(Context context) {
// return OpenHelperManager.getHelper(context, DBHelper.class);
// }
//
// /**
// * This is called when the database is first created. Usually you should call createTable statements here to create
// * the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, SiteSettings.class);
// TableUtils.createTable(connectionSource, SiteCall.class);
// Log.i(DBHelper.class.getName(), "database created");
// } catch (SQLException e) {
// Log.e(TAG, "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// /**
// * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
// * the various data to match the new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// try {
// Dao<SiteSettings, Long> dao = getDao(SiteSettings.class);
// dao.executeRaw("ALTER TABLE `sitesettings` ADD COLUMN internalUrl VARCHAR;");
// } catch (SQLException e) {
// Log.e(TAG, "onUpgrade < 2, oldVersion: " + oldVersion + " newVersion: " + newVersion, e);
// }
// }
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// }
//
// public DBSiteSettings getDBSiteSettings() throws SQLException {
// return new DBSiteSettings(this.<Dao<SiteSettings, Long>, SiteSettings>getDao(SiteSettings.class));
// }
//
// public DBSiteCall getDBSiteCall() throws SQLException {
// return new DBSiteCall(this.<Dao<SiteCall, Long>, SiteCall>getDao(SiteCall.class));
// }
//
//
// /**
// * Must be call by each entities that has call #getHelper before when no more using it.
// */
// public void release() {
// OpenHelperManager.releaseHelper();
// }
// }
//
// Path: app/src/main/java/org/site_monitor/model/db/DBSiteCall.java
// public class DBSiteCall {
//
// private Dao<SiteCall, Long> dao;
//
// public DBSiteCall(Dao<SiteCall, Long> dao) {
// this.dao = dao;
// }
//
// public int create(SiteCall siteCall) throws SQLException {
// return dao.create(siteCall);
// }
//
// public int removeCallsBefore(Date date) throws SQLException {
// return dao.delete((PreparedDelete<SiteCall>) dao.deleteBuilder().where().lt("date", date).prepare());
// }
// }
// Path: app/src/main/java/org/site_monitor/service/PurgeDbService.java
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import org.site_monitor.BuildConfig;
import org.site_monitor.model.db.DBHelper;
import org.site_monitor.model.db.DBSiteCall;
import java.sql.SQLException;
import java.util.Calendar;
/*
* Copyright (c) 2016 Martin Norbert
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.site_monitor.service;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
*/
public class PurgeDbService extends JobIntentService {
private static final String ACTION_PURGE_CALLS = "org.site_monitor.service.action.PURGE_CALLS";
private static final String TAG = PurgeDbService.class.getSimpleName();
public static Intent intent(Context context) {
return new Intent(context, PurgeDbService.class).setAction(ACTION_PURGE_CALLS);
}
/**
* Called serially for each work dispatched to and processed by the service. This
* method is called on a background thread, so you can do long blocking operations
* here. Upon returning, that work will be considered complete and either the next
* pending work dispatched here or the overall service destroyed now that it has
* nothing else to do.
* <p>
* <p>Be aware that when running as a job, you are limited by the maximum job execution
* time and any single or total sequential items of work that exceeds that limit will
* cause the service to be stopped while in progress and later restarted with the
* last unfinished work. (There is currently no limit on execution duration when
* running as a pre-O plain Service.)</p>
*
* @param intent The intent describing the work to now be processed.
*/
@Override
protected void onHandleWork(@NonNull Intent intent) {
final String action = intent.getAction();
if (action == null) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "onHandleIntent: no action");
}
return;
}
if (ACTION_PURGE_CALLS.equals(action)) {
purgeCalls();
}
}
private void purgeCalls() {
try {
DBHelper dbHelper = DBHelper.getHelper(this); | DBSiteCall dbSiteCall = dbHelper.getDBSiteCall(); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/model/ModelStateMap.java | // Path: stavor/src/main/java/cs/si/stavor/model/ModelSimulation.java
// class MapPoint{
// public MapPoint(double lat, double lon, double alt){
// latitude = lat;
// longitude = lon;
// altitude = alt;
// }
// double latitude = 0;
// double longitude = 0;
// double altitude = 0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/LatLon.java
// public class LatLon {
// public double latitude = 0.0;
// public double longitude = 0.0;
//
// public LatLon(double latitude, double longitude){
// this.latitude = latitude;
// this.longitude = longitude;
// }
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationArea.java
// public class StationArea {
// public String name = "Station";
// public double station_longitude = 0.0;
// public LatLon[] points;
// public int type = 0;// 0 closed area, 1 nord pole area, 2 south pole area
//
// public StationArea(String name, double longitude, LatLon[] points, int type){
// this.name = name;
// this.points = points;
// this.station_longitude = longitude;
// this.type = type;
// }
// }
| import java.io.Serializable;
import cs.si.stavor.model.ModelSimulation.MapPoint;
import cs.si.stavor.station.LatLon;
import cs.si.stavor.station.StationArea; | package cs.si.stavor.model;
/**
* Parameters for the periodic model representation.
* @author Xavier Gibert
*
*/
public class ModelStateMap implements Serializable{
public MapPoint point; | // Path: stavor/src/main/java/cs/si/stavor/model/ModelSimulation.java
// class MapPoint{
// public MapPoint(double lat, double lon, double alt){
// latitude = lat;
// longitude = lon;
// altitude = alt;
// }
// double latitude = 0;
// double longitude = 0;
// double altitude = 0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/LatLon.java
// public class LatLon {
// public double latitude = 0.0;
// public double longitude = 0.0;
//
// public LatLon(double latitude, double longitude){
// this.latitude = latitude;
// this.longitude = longitude;
// }
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationArea.java
// public class StationArea {
// public String name = "Station";
// public double station_longitude = 0.0;
// public LatLon[] points;
// public int type = 0;// 0 closed area, 1 nord pole area, 2 south pole area
//
// public StationArea(String name, double longitude, LatLon[] points, int type){
// this.name = name;
// this.points = points;
// this.station_longitude = longitude;
// this.type = type;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/model/ModelStateMap.java
import java.io.Serializable;
import cs.si.stavor.model.ModelSimulation.MapPoint;
import cs.si.stavor.station.LatLon;
import cs.si.stavor.station.StationArea;
package cs.si.stavor.model;
/**
* Parameters for the periodic model representation.
* @author Xavier Gibert
*
*/
public class ModelStateMap implements Serializable{
public MapPoint point; | public LatLon[] fov, fov_terminator, terminator; |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/model/ModelStateMap.java | // Path: stavor/src/main/java/cs/si/stavor/model/ModelSimulation.java
// class MapPoint{
// public MapPoint(double lat, double lon, double alt){
// latitude = lat;
// longitude = lon;
// altitude = alt;
// }
// double latitude = 0;
// double longitude = 0;
// double altitude = 0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/LatLon.java
// public class LatLon {
// public double latitude = 0.0;
// public double longitude = 0.0;
//
// public LatLon(double latitude, double longitude){
// this.latitude = latitude;
// this.longitude = longitude;
// }
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationArea.java
// public class StationArea {
// public String name = "Station";
// public double station_longitude = 0.0;
// public LatLon[] points;
// public int type = 0;// 0 closed area, 1 nord pole area, 2 south pole area
//
// public StationArea(String name, double longitude, LatLon[] points, int type){
// this.name = name;
// this.points = points;
// this.station_longitude = longitude;
// this.type = type;
// }
// }
| import java.io.Serializable;
import cs.si.stavor.model.ModelSimulation.MapPoint;
import cs.si.stavor.station.LatLon;
import cs.si.stavor.station.StationArea; | package cs.si.stavor.model;
/**
* Parameters for the periodic model representation.
* @author Xavier Gibert
*
*/
public class ModelStateMap implements Serializable{
public MapPoint point;
public LatLon[] fov, fov_terminator, terminator;
public int fov_type = 0;
public double sun_lat=0, sun_lon=0;
| // Path: stavor/src/main/java/cs/si/stavor/model/ModelSimulation.java
// class MapPoint{
// public MapPoint(double lat, double lon, double alt){
// latitude = lat;
// longitude = lon;
// altitude = alt;
// }
// double latitude = 0;
// double longitude = 0;
// double altitude = 0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/LatLon.java
// public class LatLon {
// public double latitude = 0.0;
// public double longitude = 0.0;
//
// public LatLon(double latitude, double longitude){
// this.latitude = latitude;
// this.longitude = longitude;
// }
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationArea.java
// public class StationArea {
// public String name = "Station";
// public double station_longitude = 0.0;
// public LatLon[] points;
// public int type = 0;// 0 closed area, 1 nord pole area, 2 south pole area
//
// public StationArea(String name, double longitude, LatLon[] points, int type){
// this.name = name;
// this.points = points;
// this.station_longitude = longitude;
// this.type = type;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/model/ModelStateMap.java
import java.io.Serializable;
import cs.si.stavor.model.ModelSimulation.MapPoint;
import cs.si.stavor.station.LatLon;
import cs.si.stavor.station.StationArea;
package cs.si.stavor.model;
/**
* Parameters for the periodic model representation.
* @author Xavier Gibert
*
*/
public class ModelStateMap implements Serializable{
public MapPoint point;
public LatLon[] fov, fov_terminator, terminator;
public int fov_type = 0;
public double sun_lat=0, sun_lon=0;
| public StationArea[] stations; |
CS-SI/Stavor | stavor/src/main/java/org/nikkii/embedhttp/impl/HttpRequest.java | // Path: stavor/src/main/java/org/nikkii/embedhttp/util/HttpUtil.java
// public class HttpUtil {
// /**
// * Parse POST data or GET data from the request URI
// *
// * @param data
// * The data string
// * @return A map containing the values
// */
// public static Map<String, Object> parseData(String data) {
// Map<String, Object> ret = new HashMap<String, Object>();
// String[] split = data.split("&");
// for (String s : split) {
// int idx = s.indexOf('=');
// try {
// if (idx != -1) {
// ret.put(URLDecoder.decode(s.substring(0, idx), "UTF-8"), URLDecoder.decode(s.substring(idx + 1), "UTF-8"));
// } else {
// ret.put(URLDecoder.decode(s, "UTF-8"), "true");
// }
// } catch (UnsupportedEncodingException e) {
// // Why.
// }
// }
// return ret;
// }
//
// /**
// * Fixes capitalization on headers
// *
// * @param header
// * The header input
// * @return A header with all characters after '-' capitalized
// */
// public static String capitalizeHeader(String header) {
// StringTokenizer st = new StringTokenizer(header, "-");
// StringBuilder out = new StringBuilder();
// while (st.hasMoreTokens()) {
// String l = st.nextToken();
// out.append(Character.toUpperCase(l.charAt(0)));
// if (l.length() > 1) {
// out.append(l.substring(1));
// }
// if (st.hasMoreTokens())
// out.append('-');
// }
// return out.toString();
// }
// }
| import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nikkii.embedhttp.util.HttpUtil; | package org.nikkii.embedhttp.impl;
/**
* Represents an Http request
*
* @author Nikki
*
*/
public class HttpRequest {
/**
* The session which constructed this request
*/
private HttpSession session;
/**
* The request method
*/
private HttpMethod method;
/**
* The requested URI
*/
private String uri;
/**
* The request headers
*/
private Map<String, String> headers;
/**
* Raw Query String
*/
private String queryString;
/**
* Raw POST data (Not applicable for form-encoded, automatically parsed)
*/
private String data;
/**
* The parsed GET data
*/
private Map<String, Object> getData;
/**
* The parsed POST data
*/
private Map<String, Object> postData;
/**
* The list of parsed cookies
*/
private Map<String, HttpCookie> cookies;
/**
* Construct a new HTTP request
*
* @param session
* The session which initiated the request
* @param method
* The method used to request this page
* @param uri
* The URI of the request
* @param headers
* The request headers
*/
public HttpRequest(HttpSession session, HttpMethod method, String uri, Map<String, String> headers) {
this.session = session;
this.method = method;
this.uri = uri;
this.headers = headers;
}
/**
* Get the session which initiated this request
*
* @return The session
*/
public HttpSession getSession() {
return session;
}
/**
* Get the request method
*
* @return The request method
*/
public HttpMethod getMethod() {
return method;
}
/**
* Get the request uri
*
* @return The request uri
*/
public String getUri() {
return uri;
}
/**
* Get the request headers
*
* @return The request headers
*/
public Map<String, String> getHeaders() {
return headers;
}
/**
* Gets a request header
* @param key
* The request header key
* @return
* The header value
*/
public String getHeader(String key) { | // Path: stavor/src/main/java/org/nikkii/embedhttp/util/HttpUtil.java
// public class HttpUtil {
// /**
// * Parse POST data or GET data from the request URI
// *
// * @param data
// * The data string
// * @return A map containing the values
// */
// public static Map<String, Object> parseData(String data) {
// Map<String, Object> ret = new HashMap<String, Object>();
// String[] split = data.split("&");
// for (String s : split) {
// int idx = s.indexOf('=');
// try {
// if (idx != -1) {
// ret.put(URLDecoder.decode(s.substring(0, idx), "UTF-8"), URLDecoder.decode(s.substring(idx + 1), "UTF-8"));
// } else {
// ret.put(URLDecoder.decode(s, "UTF-8"), "true");
// }
// } catch (UnsupportedEncodingException e) {
// // Why.
// }
// }
// return ret;
// }
//
// /**
// * Fixes capitalization on headers
// *
// * @param header
// * The header input
// * @return A header with all characters after '-' capitalized
// */
// public static String capitalizeHeader(String header) {
// StringTokenizer st = new StringTokenizer(header, "-");
// StringBuilder out = new StringBuilder();
// while (st.hasMoreTokens()) {
// String l = st.nextToken();
// out.append(Character.toUpperCase(l.charAt(0)));
// if (l.length() > 1) {
// out.append(l.substring(1));
// }
// if (st.hasMoreTokens())
// out.append('-');
// }
// return out.toString();
// }
// }
// Path: stavor/src/main/java/org/nikkii/embedhttp/impl/HttpRequest.java
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nikkii.embedhttp.util.HttpUtil;
package org.nikkii.embedhttp.impl;
/**
* Represents an Http request
*
* @author Nikki
*
*/
public class HttpRequest {
/**
* The session which constructed this request
*/
private HttpSession session;
/**
* The request method
*/
private HttpMethod method;
/**
* The requested URI
*/
private String uri;
/**
* The request headers
*/
private Map<String, String> headers;
/**
* Raw Query String
*/
private String queryString;
/**
* Raw POST data (Not applicable for form-encoded, automatically parsed)
*/
private String data;
/**
* The parsed GET data
*/
private Map<String, Object> getData;
/**
* The parsed POST data
*/
private Map<String, Object> postData;
/**
* The list of parsed cookies
*/
private Map<String, HttpCookie> cookies;
/**
* Construct a new HTTP request
*
* @param session
* The session which initiated the request
* @param method
* The method used to request this page
* @param uri
* The URI of the request
* @param headers
* The request headers
*/
public HttpRequest(HttpSession session, HttpMethod method, String uri, Map<String, String> headers) {
this.session = session;
this.method = method;
this.uri = uri;
this.headers = headers;
}
/**
* Get the session which initiated this request
*
* @return The session
*/
public HttpSession getSession() {
return session;
}
/**
* Get the request method
*
* @return The request method
*/
public HttpMethod getMethod() {
return method;
}
/**
* Get the request uri
*
* @return The request uri
*/
public String getUri() {
return uri;
}
/**
* Get the request headers
*
* @return The request headers
*/
public Map<String, String> getHeaders() {
return headers;
}
/**
* Gets a request header
* @param key
* The request header key
* @return
* The header value
*/
public String getHeader(String key) { | return headers.get(HttpUtil.capitalizeHeader(key)); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/StationActivity.java | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
| import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; | package cs.si.stavor;
/**
* Activity to edit or create the stations of the database
* @author Xavier Gibert
*
*/
public class StationActivity extends Activity{
boolean isEdit = false;
EditText tx_name, tx_lat, tx_lon, tx_alt, tx_elev;
Button button; | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/StationActivity.java
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
package cs.si.stavor;
/**
* Activity to edit or create the stations of the database
* @author Xavier Gibert
*
*/
public class StationActivity extends Activity{
boolean isEdit = false;
EditText tx_name, tx_lat, tx_lon, tx_alt, tx_elev;
Button button; | StationAndId station; |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/StationActivity.java | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
| import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; | package cs.si.stavor;
/**
* Activity to edit or create the stations of the database
* @author Xavier Gibert
*
*/
public class StationActivity extends Activity{
boolean isEdit = false;
EditText tx_name, tx_lat, tx_lon, tx_alt, tx_elev;
Button button;
StationAndId station;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.station_editor);
//Load mission, in case of edit mode, and the mode flag
Bundle b = this.getIntent().getExtras();
if(b!=null){
station = (StationAndId) b.getSerializable("STATION");
isEdit = true;
}else{ | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/StationActivity.java
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
package cs.si.stavor;
/**
* Activity to edit or create the stations of the database
* @author Xavier Gibert
*
*/
public class StationActivity extends Activity{
boolean isEdit = false;
EditText tx_name, tx_lat, tx_lon, tx_alt, tx_elev;
Button button;
StationAndId station;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.station_editor);
//Load mission, in case of edit mode, and the mode flag
Bundle b = this.getIntent().getExtras();
if(b!=null){
station = (StationAndId) b.getSerializable("STATION");
isEdit = true;
}else{ | station = new StationAndId(new GroundStation(), -1); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/StationActivity.java | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
| import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; |
//Load Views
tx_name = (EditText) findViewById(R.id.editTextStationName);
tx_name.requestFocus();
tx_lat = (EditText) findViewById(R.id.editTextStationLat);
tx_lon = (EditText) findViewById(R.id.editTextStationLon);
tx_alt = (EditText) findViewById(R.id.editTextStationAlt);
tx_elev = (EditText) findViewById(R.id.editTextStationElev);
//Fill Views
tx_lat.setText(Double.toString(station.station.latitude));
tx_lon.setText(Double.toString(station.station.longitude));
tx_alt.setText(Double.toString(station.station.altitude));
tx_elev.setText(Double.toString(station.station.elevation));
if(isEdit){
button.setText(getString(R.string.station_edit));
tx_name.setText(station.station.name);
}else{
button.setText(getString(R.string.station_create));
}
}
private boolean editStation(){
ContentValues values = new ContentValues(); | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/GroundStation.java
// public class GroundStation implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 7297608100756290938L;
// public GroundStation(boolean station_enabled, String station_name,
// double station_lat, double station_lon, double station_alt, double station_elev) {
// enabled = station_enabled;
// name = station_name;
// latitude = station_lat;
// longitude = station_lon;
// altitude = station_alt;
// elevation = station_elev;
//
// }
// public GroundStation() {
// }
// public boolean enabled = false;
// public String name = "";
// public double latitude = 0.0;
// public double longitude = 0.0;
// public double altitude = 0.0;//m
// public double elevation = 5.0;
// }
//
// Path: stavor/src/main/java/cs/si/stavor/station/StationAndId.java
// public class StationAndId implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public GroundStation station;
// public int id;
//
// public StationAndId(GroundStation gs, int identif){
// station=gs;
// id=identif;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/StationActivity.java
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import cs.si.stavor.station.GroundStation;
import cs.si.stavor.station.StationAndId;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
//Load Views
tx_name = (EditText) findViewById(R.id.editTextStationName);
tx_name.requestFocus();
tx_lat = (EditText) findViewById(R.id.editTextStationLat);
tx_lon = (EditText) findViewById(R.id.editTextStationLon);
tx_alt = (EditText) findViewById(R.id.editTextStationAlt);
tx_elev = (EditText) findViewById(R.id.editTextStationElev);
//Fill Views
tx_lat.setText(Double.toString(station.station.latitude));
tx_lon.setText(Double.toString(station.station.longitude));
tx_alt.setText(Double.toString(station.station.altitude));
tx_elev.setText(Double.toString(station.station.elevation));
if(isEdit){
button.setText(getString(R.string.station_edit));
tx_name.setText(station.station.name);
}else{
button.setText(getString(R.string.station_create));
}
}
private boolean editStation(){
ContentValues values = new ContentValues(); | values.put(StationEntry.COLUMN_NAME_NAME, station.station.name); |
CS-SI/Stavor | stavor/src/main/java/unused/UAJscriptHandler.java | // Path: stavor/src/main/java/cs/si/stavor/StavorApplication.java
// public class StavorApplication extends MultiDexApplication {
// private String searchTerm = "";
//
// /**
// * Used to store the last screen title. For use in restoreActionBar()
// */
// public CharSequence mTitle;
// public int currentSection;
//
// //Global database objects (for multi-activity access)
// public ReaderDbHelper db_help;
// public SQLiteCursorLoader loader = null;
// public SQLiteDatabase db;
//
// public int modelViewId = R.id.menu_views_ref_frame_xyz;
// public int modelOrbitViewId = R.id.menu_orbviews_free;
//
// WebAppInterface jsInterface;
//
// public int follow_sc = R.id.menu_mapviews_free;
// public int zoom = 1;
// public float lon = (float) 0.0;
// public float lat = (float) 0.0;
//
// public void setSearchTerm(String searchTerm) {
// this.searchTerm = searchTerm;
// }
//
// public String getSearchTerm() {
// return this.searchTerm;
// }
//
// }
| import cs.si.stavor.StavorApplication;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.widget.Toast; | package unused;
public class UAJscriptHandler {
//private String tag = "UAJscriptHandler";
private Context context = null;
public UAJscriptHandler(Context context) {
//Log.i(tag,"script handler created");
this.context = context;
}
public void Log(String s) {
//Log.i(tag,s);
}
public void Info(String s) {
Toast.makeText(context,s,Toast.LENGTH_LONG).show();
}
public void PlaceCall(String number) {
//Log.i(tag,"Placing a phone call to [" + number + "]");
String url = "tel:" + number;
Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse(url));
context.startActivity(callIntent);
}
public void SetSearchTerm(String searchTerm) { | // Path: stavor/src/main/java/cs/si/stavor/StavorApplication.java
// public class StavorApplication extends MultiDexApplication {
// private String searchTerm = "";
//
// /**
// * Used to store the last screen title. For use in restoreActionBar()
// */
// public CharSequence mTitle;
// public int currentSection;
//
// //Global database objects (for multi-activity access)
// public ReaderDbHelper db_help;
// public SQLiteCursorLoader loader = null;
// public SQLiteDatabase db;
//
// public int modelViewId = R.id.menu_views_ref_frame_xyz;
// public int modelOrbitViewId = R.id.menu_orbviews_free;
//
// WebAppInterface jsInterface;
//
// public int follow_sc = R.id.menu_mapviews_free;
// public int zoom = 1;
// public float lon = (float) 0.0;
// public float lat = (float) 0.0;
//
// public void setSearchTerm(String searchTerm) {
// this.searchTerm = searchTerm;
// }
//
// public String getSearchTerm() {
// return this.searchTerm;
// }
//
// }
// Path: stavor/src/main/java/unused/UAJscriptHandler.java
import cs.si.stavor.StavorApplication;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.widget.Toast;
package unused;
public class UAJscriptHandler {
//private String tag = "UAJscriptHandler";
private Context context = null;
public UAJscriptHandler(Context context) {
//Log.i(tag,"script handler created");
this.context = context;
}
public void Log(String s) {
//Log.i(tag,s);
}
public void Info(String s) {
Toast.makeText(context,s,Toast.LENGTH_LONG).show();
}
public void PlaceCall(String number) {
//Log.i(tag,"Placing a phone call to [" + number + "]");
String url = "tel:" + number;
Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse(url));
context.startActivity(callIntent);
}
public void SetSearchTerm(String searchTerm) { | StavorApplication app = (StavorApplication) context.getApplicationContext(); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/database/StationsCursorAdapter.java | // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
| import com.commonsware.cwac.loaderex.SQLiteCursorLoader;
import cs.si.stavor.R;
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView; | package cs.si.stavor.database;
public class StationsCursorAdapter extends CursorAdapter {
private SQLiteCursorLoader loader;
private int mSelectedPosition;
LayoutInflater mInflater;
public StationsCursorAdapter(Context context, Cursor c, SQLiteCursorLoader cloader) {
// that constructor should be used with loaders.
super(context, c, 0);
mInflater = LayoutInflater.from(context);
loader = cloader;
}
public void setSelectedPosition(int position) {
mSelectedPosition = position;
// something has changed.
notifyDataSetChanged();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView list_item_id = (TextView)view.findViewById(R.id.textViewStationId);
TextView list_item_name = (TextView)view.findViewById(R.id.textViewStationName);
CheckBox list_item_enabled = (CheckBox)view.findViewById(R.id.checkBoxStationEnabled);
list_item_enabled.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
String entry = "0";
if(arg1){
entry = "1";
}
String db_id = list_item_id.getText().toString();
updateStationEnabled(db_id, entry);
}
});
| // Path: stavor/src/main/java/cs/si/stavor/database/StationsReaderContract.java
// public static abstract class StationEntry implements BaseColumns {
// public static final String TABLE_NAME = "station";
// public static final String COLUMN_NAME_ENABLED = "enabled";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_LATITUDE = "latitude";
// public static final String COLUMN_NAME_LONGITUDE = "longitude";
// public static final String COLUMN_NAME_ALTITUDE = "altitude";
// public static final String COLUMN_NAME_ELEVATION = "elevation";
// }
// Path: stavor/src/main/java/cs/si/stavor/database/StationsCursorAdapter.java
import com.commonsware.cwac.loaderex.SQLiteCursorLoader;
import cs.si.stavor.R;
import cs.si.stavor.database.StationsReaderContract.StationEntry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
package cs.si.stavor.database;
public class StationsCursorAdapter extends CursorAdapter {
private SQLiteCursorLoader loader;
private int mSelectedPosition;
LayoutInflater mInflater;
public StationsCursorAdapter(Context context, Cursor c, SQLiteCursorLoader cloader) {
// that constructor should be used with loaders.
super(context, c, 0);
mInflater = LayoutInflater.from(context);
loader = cloader;
}
public void setSelectedPosition(int position) {
mSelectedPosition = position;
// something has changed.
notifyDataSetChanged();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView list_item_id = (TextView)view.findViewById(R.id.textViewStationId);
TextView list_item_name = (TextView)view.findViewById(R.id.textViewStationName);
CheckBox list_item_enabled = (CheckBox)view.findViewById(R.id.checkBoxStationEnabled);
list_item_enabled.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
String entry = "0";
if(arg1){
entry = "1";
}
String db_id = list_item_id.getText().toString();
updateStationEnabled(db_id, entry);
}
});
| list_item_id.setText(cursor.getString(cursor.getColumnIndex(StationEntry._ID))); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/SplashActivity.java | // Path: stavor/src/main/java/cs/si/stavor/app/Parameters.java
// public class Parameters {
// /**
// * General application parameters
// * @author Xavier Gibert
// *
// */
// public static class App {
//
// public static final int splash_min_time_ms = 3000;//[ms] 3.0s min
// public static final boolean show_tests_section = false;
// public static final boolean pro_version = false;
//
// //FIRST RUN PARAMETERS
// public static final boolean show_guide = true;
// //Deprecated: it was the old crappy tutorial based on dialog boxes
// public static final boolean show_tutorial = false;
// public static final boolean show_orekit_data_installation_message = false;
// //If we want to show the sections menu open during the first run of the application and always until user makes use of it then set to false.
// public static final boolean first_start_app_closed_section_menu = true;
// }
// /**
// * About screen information
// * @author Xavier Gibert
// *
// */
// public static class About {
// public static final String jocs_site = "http://jocsmobile.wordpress.com";
// public static final String orekit_site = "http://orekit.org";
// public static final String project_start_date = "2014/04/01";
// public static final String version_orekit = "7.X";
// public static final String version_xwalk = "13.42.319.11s";
// public static final String version_threejs = "r67";
// public static final String version_gson = "2.2.4";
// public static final String version_androidcolorpicker = "1.0";
// public static final String version_loader = "0.7.3";
// public static final String version_openlayers = "2.13.1";
// public static final String version_http = "1.2.1";
// }
// /**
// * Visualization configuration
// * @author Xavier Gibert
// *
// */
// public static class Hud {
// public static final boolean start_panel_open = true;
// }
// /**
// * Simulator configuration
// * @author Xavier Gibert
// *
// */
// public static class Simulator {
// public static final long min_hud_panel_refreshing_interval_ns = 500000000;//[ns] 2Hz max
// public static final long min_hud_model_refreshing_interval_ns = 40000000;//[ns] 25Hz max
// public static final long model_refreshing_interval_safe_guard_ns = 5000000;//[ns] 5ms
// public static final int amount_mission_examples = 7;
// public static class Remote{
// public static final int remote_connection_timeout_ms = 5000;//[ms]
// public static final String default_host = "192.168.1.2";
// public static final String default_port = "1520";
// public static boolean default_ssl = false;
// public static int objects_per_ssl_request = 50;
// }
// }
// /**
// * URLs for the visualization and tests
// * @author Xavier Gibert
// *
// */
// public static class Web {
// public static final String STARTING_PAGE = "file:///android_asset/www/huds/index.html";
// public static final String STARTING_PAGE_ORBIT = "file:///android_asset/www/huds/index_orbit.html";
// public static final String STARTING_PAGE_MAP = "file:///android_asset/www/map/index.html";
// //public static final String TEST_PAGE_1 = "file:///android_asset/www/index.html";
// //public static final String TEST_PAGE_1 = "http://127.0.0.1:8081/";
// //public static final String TEST_PAGE_1 = "http://webglreport.com";
// public static final String TEST_PAGE_1 = "http://get.webgl.org/";
// public static final String TEST_PAGE_2 = "http://doesmybrowsersupportwebgl.com/";
// public static final String TEST_PAGE_3 = "http://www.khronos.org/registry/webgl/sdk/tests/webgl-conformance-tests.html";
// public static final String LOCALHOST = "http://localhost:8080/";
// }
// public static class Map {
// //public static final double marker_pos_threshold = 0.2;//In deg
// public static final int station_visibility_points = 30;//Points in the polygon
// public static final int satellite_fov_points = 30;//30
// public static final double solar_terminator_points = 100;
// public static final double solar_terminator_threshold = 60*15;//In seconds
// public static final int satellite_track_max_points = 100;
// }
// }
| import cs.si.stavor.app.Parameters;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler; | package cs.si.stavor;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
} | // Path: stavor/src/main/java/cs/si/stavor/app/Parameters.java
// public class Parameters {
// /**
// * General application parameters
// * @author Xavier Gibert
// *
// */
// public static class App {
//
// public static final int splash_min_time_ms = 3000;//[ms] 3.0s min
// public static final boolean show_tests_section = false;
// public static final boolean pro_version = false;
//
// //FIRST RUN PARAMETERS
// public static final boolean show_guide = true;
// //Deprecated: it was the old crappy tutorial based on dialog boxes
// public static final boolean show_tutorial = false;
// public static final boolean show_orekit_data_installation_message = false;
// //If we want to show the sections menu open during the first run of the application and always until user makes use of it then set to false.
// public static final boolean first_start_app_closed_section_menu = true;
// }
// /**
// * About screen information
// * @author Xavier Gibert
// *
// */
// public static class About {
// public static final String jocs_site = "http://jocsmobile.wordpress.com";
// public static final String orekit_site = "http://orekit.org";
// public static final String project_start_date = "2014/04/01";
// public static final String version_orekit = "7.X";
// public static final String version_xwalk = "13.42.319.11s";
// public static final String version_threejs = "r67";
// public static final String version_gson = "2.2.4";
// public static final String version_androidcolorpicker = "1.0";
// public static final String version_loader = "0.7.3";
// public static final String version_openlayers = "2.13.1";
// public static final String version_http = "1.2.1";
// }
// /**
// * Visualization configuration
// * @author Xavier Gibert
// *
// */
// public static class Hud {
// public static final boolean start_panel_open = true;
// }
// /**
// * Simulator configuration
// * @author Xavier Gibert
// *
// */
// public static class Simulator {
// public static final long min_hud_panel_refreshing_interval_ns = 500000000;//[ns] 2Hz max
// public static final long min_hud_model_refreshing_interval_ns = 40000000;//[ns] 25Hz max
// public static final long model_refreshing_interval_safe_guard_ns = 5000000;//[ns] 5ms
// public static final int amount_mission_examples = 7;
// public static class Remote{
// public static final int remote_connection_timeout_ms = 5000;//[ms]
// public static final String default_host = "192.168.1.2";
// public static final String default_port = "1520";
// public static boolean default_ssl = false;
// public static int objects_per_ssl_request = 50;
// }
// }
// /**
// * URLs for the visualization and tests
// * @author Xavier Gibert
// *
// */
// public static class Web {
// public static final String STARTING_PAGE = "file:///android_asset/www/huds/index.html";
// public static final String STARTING_PAGE_ORBIT = "file:///android_asset/www/huds/index_orbit.html";
// public static final String STARTING_PAGE_MAP = "file:///android_asset/www/map/index.html";
// //public static final String TEST_PAGE_1 = "file:///android_asset/www/index.html";
// //public static final String TEST_PAGE_1 = "http://127.0.0.1:8081/";
// //public static final String TEST_PAGE_1 = "http://webglreport.com";
// public static final String TEST_PAGE_1 = "http://get.webgl.org/";
// public static final String TEST_PAGE_2 = "http://doesmybrowsersupportwebgl.com/";
// public static final String TEST_PAGE_3 = "http://www.khronos.org/registry/webgl/sdk/tests/webgl-conformance-tests.html";
// public static final String LOCALHOST = "http://localhost:8080/";
// }
// public static class Map {
// //public static final double marker_pos_threshold = 0.2;//In deg
// public static final int station_visibility_points = 30;//Points in the polygon
// public static final int satellite_fov_points = 30;//30
// public static final double solar_terminator_points = 100;
// public static final double solar_terminator_threshold = 60*15;//In seconds
// public static final int satellite_track_max_points = 100;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/SplashActivity.java
import cs.si.stavor.app.Parameters;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
package cs.si.stavor;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
} | }, Parameters.App.splash_min_time_ms); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/mission/Mission.java | // Path: stavor/src/main/java/cs/si/stavor/mission/Orbit.java
// public class Orbit implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = -5454548599446807545L;
//
// public double mu = 3.986004415e+14;
// /**
// * Semi major axis in meters
// */
// public double a = 24396159;
// /**
// * Eccentricity
// */
// public double e = 0.72831215;
// /**
// * Inclination
// */
// public double i = Math.toRadians(7);
// /**
// * Perigee argument
// */
// public double omega = Math.toRadians(180);
// /**
// * Right ascension of ascending node
// */
// public double raan = Math.toRadians(0);
// /**
// * Mean anomaly
// */
// public double lM = 0;
//
// public Orbit(){
//
// }
// public Orbit(double o_mu,double o_a,double o_e,double o_i,double o_omega,double o_raan,double o_lM){
// mu=o_mu;
// a=o_a;
// e=o_e;
// i=o_i;
// omega=o_omega;
// raan=o_raan;
// lM=o_lM;
// }
// }
| import java.io.Serializable;
import org.orekit.time.AbsoluteDate;
import cs.si.stavor.mission.Orbit; | package cs.si.stavor.mission;
/**
* Mission object
* @author Xavier Gibert
*
*/
public class Mission implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1987145766082906026L;
public String name = "CustomMission";
public String description = "Mission description";
//public String initial_stage = "First Stage";
public PropagatorType propagatorType = PropagatorType.Keplerian;
public double sim_duration = 600000.;
public double sim_step = 60.;
public double initial_mass = 2000;
public InertialFrames inertialFrame = InertialFrames.EME2000;
//public RotatingFrames rotatingFrame = RotatingFrames.GTOD;
public AbsoluteDate initial_date = new AbsoluteDate(); | // Path: stavor/src/main/java/cs/si/stavor/mission/Orbit.java
// public class Orbit implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = -5454548599446807545L;
//
// public double mu = 3.986004415e+14;
// /**
// * Semi major axis in meters
// */
// public double a = 24396159;
// /**
// * Eccentricity
// */
// public double e = 0.72831215;
// /**
// * Inclination
// */
// public double i = Math.toRadians(7);
// /**
// * Perigee argument
// */
// public double omega = Math.toRadians(180);
// /**
// * Right ascension of ascending node
// */
// public double raan = Math.toRadians(0);
// /**
// * Mean anomaly
// */
// public double lM = 0;
//
// public Orbit(){
//
// }
// public Orbit(double o_mu,double o_a,double o_e,double o_i,double o_omega,double o_raan,double o_lM){
// mu=o_mu;
// a=o_a;
// e=o_e;
// i=o_i;
// omega=o_omega;
// raan=o_raan;
// lM=o_lM;
// }
// }
// Path: stavor/src/main/java/cs/si/stavor/mission/Mission.java
import java.io.Serializable;
import org.orekit.time.AbsoluteDate;
import cs.si.stavor.mission.Orbit;
package cs.si.stavor.mission;
/**
* Mission object
* @author Xavier Gibert
*
*/
public class Mission implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1987145766082906026L;
public String name = "CustomMission";
public String description = "Mission description";
//public String initial_stage = "First Stage";
public PropagatorType propagatorType = PropagatorType.Keplerian;
public double sim_duration = 600000.;
public double sim_step = 60.;
public double initial_mass = 2000;
public InertialFrames inertialFrame = InertialFrames.EME2000;
//public RotatingFrames rotatingFrame = RotatingFrames.GTOD;
public AbsoluteDate initial_date = new AbsoluteDate(); | public Orbit initial_orbit = new Orbit(); |
CS-SI/Stavor | stavor/src/main/java/cs/si/stavor/simulator/VTS2Orekit.java | // Path: stavor/src/main/java/cs/si/stavor/mission/Mission.java
// public class Mission implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1987145766082906026L;
//
// public String name = "CustomMission";
// public String description = "Mission description";
// //public String initial_stage = "First Stage";
// public PropagatorType propagatorType = PropagatorType.Keplerian;
// public double sim_duration = 600000.;
// public double sim_step = 60.;
// public double initial_mass = 2000;
// public InertialFrames inertialFrame = InertialFrames.EME2000;
// //public RotatingFrames rotatingFrame = RotatingFrames.GTOD;
// public AbsoluteDate initial_date = new AbsoluteDate();
// public Orbit initial_orbit = new Orbit();
// }
| import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.orekit.attitudes.Attitude;
import org.orekit.errors.OrekitException;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
import cs.si.stavor.mission.Mission; | quaternion = new Rotation(
Double.parseDouble(values[0]),
Double.parseDouble(values[1]),
Double.parseDouble(values[2]),
Double.parseDouble(values[3]),
false
);
}else if(parts[2].equals("vel")){
velocity = new Vector3D(
Double.parseDouble(values[0]),
Double.parseDouble(values[1]),
Double.parseDouble(values[2])
);
}else if(parts[2].equals("mass")){
mass = Double.parseDouble(values[0]);
}
PVCoordinates pv = new PVCoordinates(position, velocity);
Orbit orbit = new KeplerianOrbit(pv, old_state.getFrame(), date, old_state.getMu());
Attitude attitude = new Attitude(date, old_state.getFrame(), quaternion, null, null);
SpacecraftState state = new SpacecraftState(orbit, attitude, mass);
old_state = state;
return old_state;
}
return null;
}
private static SpacecraftState initializeState(SpacecraftState old_state){
if(old_state == null){
try { | // Path: stavor/src/main/java/cs/si/stavor/mission/Mission.java
// public class Mission implements Serializable{
// /**
// *
// */
// private static final long serialVersionUID = 1987145766082906026L;
//
// public String name = "CustomMission";
// public String description = "Mission description";
// //public String initial_stage = "First Stage";
// public PropagatorType propagatorType = PropagatorType.Keplerian;
// public double sim_duration = 600000.;
// public double sim_step = 60.;
// public double initial_mass = 2000;
// public InertialFrames inertialFrame = InertialFrames.EME2000;
// //public RotatingFrames rotatingFrame = RotatingFrames.GTOD;
// public AbsoluteDate initial_date = new AbsoluteDate();
// public Orbit initial_orbit = new Orbit();
// }
// Path: stavor/src/main/java/cs/si/stavor/simulator/VTS2Orekit.java
import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.orekit.attitudes.Attitude;
import org.orekit.errors.OrekitException;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.SpacecraftState;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
import cs.si.stavor.mission.Mission;
quaternion = new Rotation(
Double.parseDouble(values[0]),
Double.parseDouble(values[1]),
Double.parseDouble(values[2]),
Double.parseDouble(values[3]),
false
);
}else if(parts[2].equals("vel")){
velocity = new Vector3D(
Double.parseDouble(values[0]),
Double.parseDouble(values[1]),
Double.parseDouble(values[2])
);
}else if(parts[2].equals("mass")){
mass = Double.parseDouble(values[0]);
}
PVCoordinates pv = new PVCoordinates(position, velocity);
Orbit orbit = new KeplerianOrbit(pv, old_state.getFrame(), date, old_state.getMu());
Attitude attitude = new Attitude(date, old_state.getFrame(), quaternion, null, null);
SpacecraftState state = new SpacecraftState(orbit, attitude, mass);
old_state = state;
return old_state;
}
return null;
}
private static SpacecraftState initializeState(SpacecraftState old_state){
if(old_state == null){
try { | Mission mission = new Mission(); |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/ClazzCreator.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.IOException; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/19/17 = 1:35 PM
*/
public class ClazzCreator {
public static void main(String args[]) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/ClazzCreator.java
import com.io.bio.file.FileUtils;
import java.io.IOException;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/19/17 = 1:35 PM
*/
public class ClazzCreator {
public static void main(String args[]) throws IOException { | String data = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/thread/pool/SimpleThreadPool.java | // Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
//
// Path: jdklib/src/main/java/com/current/queue/jdkAPI/ArraysSynchronizedQueue.java
// public class ArraysSynchronizedQueue<T> implements BlockingQueue<T>{
// private Logger logger = Logger.getLogger(ArraysSynchronizedQueue.class.getName());
// private static int DEFAULT_SIZE = 100;
// private int arraySize;
// private int putIndex;
// private int takeIndex;
// private int size;
// private Byte[] lock;
// private Object[] obj;
//
// public ArraysSynchronizedQueue(){
// this(DEFAULT_SIZE);
// }
//
// public ArraysSynchronizedQueue(int arraySize){
// this.arraySize = arraySize;
// initialize();
// }
//
// private void initialize(){
// lock = new Byte[0];
// obj = new Object[arraySize];
// putIndex = 0;
// takeIndex = 0;
// size = 0;
// }
//
// @Override
// public T take() throws InterruptedException{
// synchronized (lock){
// while (size == 0){
// logger.log(Level.INFO, "queue is empty");
// lock.wait();
// }
// T result = (T)obj[takeIndex++];
// size --;
// takeIndex = setIndex(takeIndex);
// lock.notifyAll();
// return result;
// }
// }
//
// @Override
// public void put(T object) throws InterruptedException{
// synchronized (lock){
// while (size == arraySize){
// logger.log(Level.INFO, "queue is full");
// lock.wait();
// }
// obj[putIndex++] = object;
// size++;
// putIndex = setIndex(putIndex);
// lock.notifyAll();
// }
// }
//
// private int setIndex(int index){
// if(index >= arraySize){
// return 0;
// }
// return index;
// }
//
// }
| import com.current.queue.BlockingQueue;
import com.current.queue.jdkAPI.ArraysSynchronizedQueue; | package com.current.thread.pool;
/**
* Author Mr.Pro
* Date 9/23/17 = 5:05 PM
*/
public class SimpleThreadPool<T extends Runnable> {
private static final int DEFAULT_MIN_CORE_COUNT = 2;
private static final int DEFAULT_MAX_CORE_COUNT = 4;
private int mnCore;
private int mxCore;
private Thread[] waiters; | // Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
//
// Path: jdklib/src/main/java/com/current/queue/jdkAPI/ArraysSynchronizedQueue.java
// public class ArraysSynchronizedQueue<T> implements BlockingQueue<T>{
// private Logger logger = Logger.getLogger(ArraysSynchronizedQueue.class.getName());
// private static int DEFAULT_SIZE = 100;
// private int arraySize;
// private int putIndex;
// private int takeIndex;
// private int size;
// private Byte[] lock;
// private Object[] obj;
//
// public ArraysSynchronizedQueue(){
// this(DEFAULT_SIZE);
// }
//
// public ArraysSynchronizedQueue(int arraySize){
// this.arraySize = arraySize;
// initialize();
// }
//
// private void initialize(){
// lock = new Byte[0];
// obj = new Object[arraySize];
// putIndex = 0;
// takeIndex = 0;
// size = 0;
// }
//
// @Override
// public T take() throws InterruptedException{
// synchronized (lock){
// while (size == 0){
// logger.log(Level.INFO, "queue is empty");
// lock.wait();
// }
// T result = (T)obj[takeIndex++];
// size --;
// takeIndex = setIndex(takeIndex);
// lock.notifyAll();
// return result;
// }
// }
//
// @Override
// public void put(T object) throws InterruptedException{
// synchronized (lock){
// while (size == arraySize){
// logger.log(Level.INFO, "queue is full");
// lock.wait();
// }
// obj[putIndex++] = object;
// size++;
// putIndex = setIndex(putIndex);
// lock.notifyAll();
// }
// }
//
// private int setIndex(int index){
// if(index >= arraySize){
// return 0;
// }
// return index;
// }
//
// }
// Path: jdklib/src/main/java/com/current/thread/pool/SimpleThreadPool.java
import com.current.queue.BlockingQueue;
import com.current.queue.jdkAPI.ArraysSynchronizedQueue;
package com.current.thread.pool;
/**
* Author Mr.Pro
* Date 9/23/17 = 5:05 PM
*/
public class SimpleThreadPool<T extends Runnable> {
private static final int DEFAULT_MIN_CORE_COUNT = 2;
private static final int DEFAULT_MAX_CORE_COUNT = 4;
private int mnCore;
private int mxCore;
private Thread[] waiters; | private BlockingQueue<T> blockingQueue; |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/thread/pool/SimpleThreadPool.java | // Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
//
// Path: jdklib/src/main/java/com/current/queue/jdkAPI/ArraysSynchronizedQueue.java
// public class ArraysSynchronizedQueue<T> implements BlockingQueue<T>{
// private Logger logger = Logger.getLogger(ArraysSynchronizedQueue.class.getName());
// private static int DEFAULT_SIZE = 100;
// private int arraySize;
// private int putIndex;
// private int takeIndex;
// private int size;
// private Byte[] lock;
// private Object[] obj;
//
// public ArraysSynchronizedQueue(){
// this(DEFAULT_SIZE);
// }
//
// public ArraysSynchronizedQueue(int arraySize){
// this.arraySize = arraySize;
// initialize();
// }
//
// private void initialize(){
// lock = new Byte[0];
// obj = new Object[arraySize];
// putIndex = 0;
// takeIndex = 0;
// size = 0;
// }
//
// @Override
// public T take() throws InterruptedException{
// synchronized (lock){
// while (size == 0){
// logger.log(Level.INFO, "queue is empty");
// lock.wait();
// }
// T result = (T)obj[takeIndex++];
// size --;
// takeIndex = setIndex(takeIndex);
// lock.notifyAll();
// return result;
// }
// }
//
// @Override
// public void put(T object) throws InterruptedException{
// synchronized (lock){
// while (size == arraySize){
// logger.log(Level.INFO, "queue is full");
// lock.wait();
// }
// obj[putIndex++] = object;
// size++;
// putIndex = setIndex(putIndex);
// lock.notifyAll();
// }
// }
//
// private int setIndex(int index){
// if(index >= arraySize){
// return 0;
// }
// return index;
// }
//
// }
| import com.current.queue.BlockingQueue;
import com.current.queue.jdkAPI.ArraysSynchronizedQueue; | package com.current.thread.pool;
/**
* Author Mr.Pro
* Date 9/23/17 = 5:05 PM
*/
public class SimpleThreadPool<T extends Runnable> {
private static final int DEFAULT_MIN_CORE_COUNT = 2;
private static final int DEFAULT_MAX_CORE_COUNT = 4;
private int mnCore;
private int mxCore;
private Thread[] waiters;
private BlockingQueue<T> blockingQueue;
public SimpleThreadPool(){ | // Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
//
// Path: jdklib/src/main/java/com/current/queue/jdkAPI/ArraysSynchronizedQueue.java
// public class ArraysSynchronizedQueue<T> implements BlockingQueue<T>{
// private Logger logger = Logger.getLogger(ArraysSynchronizedQueue.class.getName());
// private static int DEFAULT_SIZE = 100;
// private int arraySize;
// private int putIndex;
// private int takeIndex;
// private int size;
// private Byte[] lock;
// private Object[] obj;
//
// public ArraysSynchronizedQueue(){
// this(DEFAULT_SIZE);
// }
//
// public ArraysSynchronizedQueue(int arraySize){
// this.arraySize = arraySize;
// initialize();
// }
//
// private void initialize(){
// lock = new Byte[0];
// obj = new Object[arraySize];
// putIndex = 0;
// takeIndex = 0;
// size = 0;
// }
//
// @Override
// public T take() throws InterruptedException{
// synchronized (lock){
// while (size == 0){
// logger.log(Level.INFO, "queue is empty");
// lock.wait();
// }
// T result = (T)obj[takeIndex++];
// size --;
// takeIndex = setIndex(takeIndex);
// lock.notifyAll();
// return result;
// }
// }
//
// @Override
// public void put(T object) throws InterruptedException{
// synchronized (lock){
// while (size == arraySize){
// logger.log(Level.INFO, "queue is full");
// lock.wait();
// }
// obj[putIndex++] = object;
// size++;
// putIndex = setIndex(putIndex);
// lock.notifyAll();
// }
// }
//
// private int setIndex(int index){
// if(index >= arraySize){
// return 0;
// }
// return index;
// }
//
// }
// Path: jdklib/src/main/java/com/current/thread/pool/SimpleThreadPool.java
import com.current.queue.BlockingQueue;
import com.current.queue.jdkAPI.ArraysSynchronizedQueue;
package com.current.thread.pool;
/**
* Author Mr.Pro
* Date 9/23/17 = 5:05 PM
*/
public class SimpleThreadPool<T extends Runnable> {
private static final int DEFAULT_MIN_CORE_COUNT = 2;
private static final int DEFAULT_MAX_CORE_COUNT = 4;
private int mnCore;
private int mxCore;
private Thread[] waiters;
private BlockingQueue<T> blockingQueue;
public SimpleThreadPool(){ | this(DEFAULT_MIN_CORE_COUNT, DEFAULT_MAX_CORE_COUNT, new ArraysSynchronizedQueue<T>()); |
caoyj1991/Core-Java | jdklib/src/main/java/com/json/HttpResponseUtil.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function; | package com.json;
/**
* Author Mr.Pro
* Date 9/11/17 = 11:14 AM
*/
public class HttpResponseUtil {
public static void main(String[] arg) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/json/HttpResponseUtil.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function;
package com.json;
/**
* Author Mr.Pro
* Date 9/11/17 = 11:14 AM
*/
public class HttpResponseUtil {
public static void main(String[] arg) throws IOException { | String jsonString = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | framework/src/main/java/com/framework/webdevelop/annotation/RequestMapping.java | // Path: framework/src/main/java/com/network/protocol/http/HttpMethod.java
// public class HttpMethod {
//
// public enum Type{
// GET,
// POST,
// PUT,
// DELETE;
// }
//
// public static Type resolver(String methodWord){
// switch (methodWord){
// case "GET":
// return Type.GET;
// case "POST":
// return Type.POST;
// case "PUT":
// return Type.PUT;
// case "DELETE":
// return Type.DELETE;
// default:
// throw new UnsupportedOperationException("do not support it method type is :"+methodWord);
// }
// }
// }
| import com.network.protocol.http.HttpMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.framework.webdevelop.annotation;
/**
* Author Jun
* Email
* Date 6/25/17
* Time 1:03 PM
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String uri() default "/"; | // Path: framework/src/main/java/com/network/protocol/http/HttpMethod.java
// public class HttpMethod {
//
// public enum Type{
// GET,
// POST,
// PUT,
// DELETE;
// }
//
// public static Type resolver(String methodWord){
// switch (methodWord){
// case "GET":
// return Type.GET;
// case "POST":
// return Type.POST;
// case "PUT":
// return Type.PUT;
// case "DELETE":
// return Type.DELETE;
// default:
// throw new UnsupportedOperationException("do not support it method type is :"+methodWord);
// }
// }
// }
// Path: framework/src/main/java/com/framework/webdevelop/annotation/RequestMapping.java
import com.network.protocol.http.HttpMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.framework.webdevelop.annotation;
/**
* Author Jun
* Email
* Date 6/25/17
* Time 1:03 PM
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String uri() default "/"; | HttpMethod.Type method() default HttpMethod.Type.GET; |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// @Data
// @Accessors(chain = true)
// public class Node {
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
//
// private Type type;
// private Thread thread;
// private Node nextNode;
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
| import com.current.lock.Lock;
import com.current.lock.Node;
import com.current.lock.Node.Type;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger; | package com.current.lock.v3;
/**
* Author Mr.Pro
* Date 9/10/17 = 6:10 PM
*/
public class SynchronizedShareLock implements Lock {
private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
| // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// @Data
// @Accessors(chain = true)
// public class Node {
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
//
// private Type type;
// private Thread thread;
// private Node nextNode;
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
// Path: jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java
import com.current.lock.Lock;
import com.current.lock.Node;
import com.current.lock.Node.Type;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
package com.current.lock.v3;
/**
* Author Mr.Pro
* Date 9/10/17 = 6:10 PM
*/
public class SynchronizedShareLock implements Lock {
private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
| private volatile Type nodeType = null; |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// @Data
// @Accessors(chain = true)
// public class Node {
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
//
// private Type type;
// private Thread thread;
// private Node nextNode;
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
| import com.current.lock.Lock;
import com.current.lock.Node;
import com.current.lock.Node.Type;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger; | package com.current.lock.v3;
/**
* Author Mr.Pro
* Date 9/10/17 = 6:10 PM
*/
public class SynchronizedShareLock implements Lock {
private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
private volatile Type nodeType = null;
private AtomicInteger count; | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// @Data
// @Accessors(chain = true)
// public class Node {
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
//
// private Type type;
// private Thread thread;
// private Node nextNode;
// }
//
// Path: jdklib/src/main/java/com/current/lock/Node.java
// public enum Type{
// SHARE,
// SINGLE,
// TERMINATE
// }
// Path: jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java
import com.current.lock.Lock;
import com.current.lock.Node;
import com.current.lock.Node.Type;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
package com.current.lock.v3;
/**
* Author Mr.Pro
* Date 9/10/17 = 6:10 PM
*/
public class SynchronizedShareLock implements Lock {
private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
private volatile Type nodeType = null;
private AtomicInteger count; | private Node headNode, tailNode; |
caoyj1991/Core-Java | framework/src/main/java/com/network/sorket/blockingio/SocketThreadExecutor.java | // Path: framework/src/main/java/com/exception/ServerException.java
// public class ServerException extends Exception {
//
// private String message;
//
// public ServerException(String message){
// super(message);
// }
// }
| import com.exception.ServerException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; | package com.network.sorket.blockingio;
/**
* Author Jun
* Email
* Date 6/24/17
* Time 3:48 PM
*/
public class SocketThreadExecutor {
private static volatile SocketThreadExecutor instance;
private Executor executor;
private final int THREAD_CORE_COUNT = 4;
private final int THREAD_MAX_COUNT = 8;
private final long THREAD_KEEP_ALIVE = 500;
private final int BLOCKING_MAX_COUNT = 1000;
public SocketThreadExecutor(){
executor= new ThreadPoolExecutor(THREAD_CORE_COUNT, THREAD_MAX_COUNT, THREAD_KEEP_ALIVE, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(BLOCKING_MAX_COUNT));
}
public static SocketThreadExecutor getInstance(){
if(instance == null){
synchronized (SocketThreadExecutor.class){
if(instance == null){
instance = new SocketThreadExecutor();
}
}
}
return instance;
}
| // Path: framework/src/main/java/com/exception/ServerException.java
// public class ServerException extends Exception {
//
// private String message;
//
// public ServerException(String message){
// super(message);
// }
// }
// Path: framework/src/main/java/com/network/sorket/blockingio/SocketThreadExecutor.java
import com.exception.ServerException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
package com.network.sorket.blockingio;
/**
* Author Jun
* Email
* Date 6/24/17
* Time 3:48 PM
*/
public class SocketThreadExecutor {
private static volatile SocketThreadExecutor instance;
private Executor executor;
private final int THREAD_CORE_COUNT = 4;
private final int THREAD_MAX_COUNT = 8;
private final long THREAD_KEEP_ALIVE = 500;
private final int BLOCKING_MAX_COUNT = 1000;
public SocketThreadExecutor(){
executor= new ThreadPoolExecutor(THREAD_CORE_COUNT, THREAD_MAX_COUNT, THREAD_KEEP_ALIVE, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(BLOCKING_MAX_COUNT));
}
public static SocketThreadExecutor getInstance(){
if(instance == null){
synchronized (SocketThreadExecutor.class){
if(instance == null){
instance = new SocketThreadExecutor();
}
}
}
return instance;
}
| public void execute(Runnable runnable) throws ServerException { |
caoyj1991/Core-Java | framework/src/main/java/com/network/sorket/blockingio/BlockingSocketService.java | // Path: framework/src/main/java/com/exception/ServerException.java
// public class ServerException extends Exception {
//
// private String message;
//
// public ServerException(String message){
// super(message);
// }
// }
| import com.exception.ServerException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; | package com.network.sorket.blockingio;
/**
* Author Jun
* Email
* Date 6/23/17
* Time 10:07 PM
*/
public class BlockingSocketService {
private final static Integer DEFAULT_PORT = 9999;
private Integer port = null;
private ServerSocket serverSocket;
private SocketConnectionService socketConnectionService;
| // Path: framework/src/main/java/com/exception/ServerException.java
// public class ServerException extends Exception {
//
// private String message;
//
// public ServerException(String message){
// super(message);
// }
// }
// Path: framework/src/main/java/com/network/sorket/blockingio/BlockingSocketService.java
import com.exception.ServerException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
package com.network.sorket.blockingio;
/**
* Author Jun
* Email
* Date 6/23/17
* Time 10:07 PM
*/
public class BlockingSocketService {
private final static Integer DEFAULT_PORT = 9999;
private Integer port = null;
private ServerSocket serverSocket;
private SocketConnectionService socketConnectionService;
| public BlockingSocketService(Integer port) throws ServerException { |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/EnumCreator.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.IOException; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/19/17 = 1:56 PM
*/
public class EnumCreator {
public static void main(String args[]) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/EnumCreator.java
import com.io.bio.file.FileUtils;
import java.io.IOException;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/19/17 = 1:56 PM
*/
public class EnumCreator {
public static void main(String args[]) throws IOException { | String data = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/queue/projectAPI/ArraysSynchronizedLockQueue.java | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/v1/SynchronizedLock.java
// public class SynchronizedLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedLock.class.getName());
//
// private Byte[] obj;
// private volatile boolean hasLock;
//
// public SynchronizedLock(){
// obj = new Byte[0];
// hasLock = false;
// }
//
// @Override
// public void lock() throws InterruptedException {
// synchronized (obj){
// while (hasLock){
// try{
// obj.wait();
// }catch (InterruptedException exception){
// logger.log(Level.WARNING, Thread.currentThread().getState().toString());
// throw new InterruptedException(exception.getMessage());
// }
// }
// hasLock = true;
// }
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// hasLock = false;
// obj.notifyAll();
// }
// }
// }
//
// Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
| import com.current.lock.Lock;
import com.current.lock.v1.SynchronizedLock;
import com.current.queue.BlockingQueue;
import java.util.logging.Logger; | package com.current.queue.projectAPI;
/**
* Author Mr.Pro
* Date 9/10/17 = 3:48 PM
*/
public class ArraysSynchronizedLockQueue<T> implements BlockingQueue<T> {
private Logger logger = Logger.getLogger(ArraysSynchronizedLockQueue.class.getName());
private static int DEFAULT_SIZE = 100;
private int arraySize;
private int putIndex;
private int takeIndex;
private int size; | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/v1/SynchronizedLock.java
// public class SynchronizedLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedLock.class.getName());
//
// private Byte[] obj;
// private volatile boolean hasLock;
//
// public SynchronizedLock(){
// obj = new Byte[0];
// hasLock = false;
// }
//
// @Override
// public void lock() throws InterruptedException {
// synchronized (obj){
// while (hasLock){
// try{
// obj.wait();
// }catch (InterruptedException exception){
// logger.log(Level.WARNING, Thread.currentThread().getState().toString());
// throw new InterruptedException(exception.getMessage());
// }
// }
// hasLock = true;
// }
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// hasLock = false;
// obj.notifyAll();
// }
// }
// }
//
// Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
// Path: jdklib/src/main/java/com/current/queue/projectAPI/ArraysSynchronizedLockQueue.java
import com.current.lock.Lock;
import com.current.lock.v1.SynchronizedLock;
import com.current.queue.BlockingQueue;
import java.util.logging.Logger;
package com.current.queue.projectAPI;
/**
* Author Mr.Pro
* Date 9/10/17 = 3:48 PM
*/
public class ArraysSynchronizedLockQueue<T> implements BlockingQueue<T> {
private Logger logger = Logger.getLogger(ArraysSynchronizedLockQueue.class.getName());
private static int DEFAULT_SIZE = 100;
private int arraySize;
private int putIndex;
private int takeIndex;
private int size; | private Lock lock; |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/queue/projectAPI/ArraysSynchronizedLockQueue.java | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/v1/SynchronizedLock.java
// public class SynchronizedLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedLock.class.getName());
//
// private Byte[] obj;
// private volatile boolean hasLock;
//
// public SynchronizedLock(){
// obj = new Byte[0];
// hasLock = false;
// }
//
// @Override
// public void lock() throws InterruptedException {
// synchronized (obj){
// while (hasLock){
// try{
// obj.wait();
// }catch (InterruptedException exception){
// logger.log(Level.WARNING, Thread.currentThread().getState().toString());
// throw new InterruptedException(exception.getMessage());
// }
// }
// hasLock = true;
// }
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// hasLock = false;
// obj.notifyAll();
// }
// }
// }
//
// Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
| import com.current.lock.Lock;
import com.current.lock.v1.SynchronizedLock;
import com.current.queue.BlockingQueue;
import java.util.logging.Logger; | package com.current.queue.projectAPI;
/**
* Author Mr.Pro
* Date 9/10/17 = 3:48 PM
*/
public class ArraysSynchronizedLockQueue<T> implements BlockingQueue<T> {
private Logger logger = Logger.getLogger(ArraysSynchronizedLockQueue.class.getName());
private static int DEFAULT_SIZE = 100;
private int arraySize;
private int putIndex;
private int takeIndex;
private int size;
private Lock lock;
private Object[] obj;
public ArraysSynchronizedLockQueue(){
this(DEFAULT_SIZE);
}
public ArraysSynchronizedLockQueue(int arraySize){
this.arraySize = arraySize;
initialize();
}
private void initialize(){ | // Path: jdklib/src/main/java/com/current/lock/Lock.java
// public interface Lock {
//
// void lock() throws InterruptedException;
// void unlock();
// }
//
// Path: jdklib/src/main/java/com/current/lock/v1/SynchronizedLock.java
// public class SynchronizedLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedLock.class.getName());
//
// private Byte[] obj;
// private volatile boolean hasLock;
//
// public SynchronizedLock(){
// obj = new Byte[0];
// hasLock = false;
// }
//
// @Override
// public void lock() throws InterruptedException {
// synchronized (obj){
// while (hasLock){
// try{
// obj.wait();
// }catch (InterruptedException exception){
// logger.log(Level.WARNING, Thread.currentThread().getState().toString());
// throw new InterruptedException(exception.getMessage());
// }
// }
// hasLock = true;
// }
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// hasLock = false;
// obj.notifyAll();
// }
// }
// }
//
// Path: jdklib/src/main/java/com/current/queue/BlockingQueue.java
// public interface BlockingQueue<T> {
//
// T take() throws InterruptedException;
//
// void put(T object) throws InterruptedException;
// }
// Path: jdklib/src/main/java/com/current/queue/projectAPI/ArraysSynchronizedLockQueue.java
import com.current.lock.Lock;
import com.current.lock.v1.SynchronizedLock;
import com.current.queue.BlockingQueue;
import java.util.logging.Logger;
package com.current.queue.projectAPI;
/**
* Author Mr.Pro
* Date 9/10/17 = 3:48 PM
*/
public class ArraysSynchronizedLockQueue<T> implements BlockingQueue<T> {
private Logger logger = Logger.getLogger(ArraysSynchronizedLockQueue.class.getName());
private static int DEFAULT_SIZE = 100;
private int arraySize;
private int putIndex;
private int takeIndex;
private int size;
private Lock lock;
private Object[] obj;
public ArraysSynchronizedLockQueue(){
this(DEFAULT_SIZE);
}
public ArraysSynchronizedLockQueue(int arraySize){
this.arraySize = arraySize;
initialize();
}
private void initialize(){ | lock = new SynchronizedLock(); |
caoyj1991/Core-Java | jdklib/src/main/java/com/utils/entity/creator/RunMain.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.List; | package com.utils.entity.creator;
/**
* Author Mr.Pro
* Date 10/10/17 = 12:31 PM
*/
public class RunMain {
public static void main(String[] args) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/utils/entity/creator/RunMain.java
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.List;
package com.utils.entity.creator;
/**
* Author Mr.Pro
* Date 10/10/17 = 12:31 PM
*/
public class RunMain {
public static void main(String[] args) throws IOException { | String sqlQuery = FileUtils.readFile("disney.sql"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/InitializedCreator.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.IOException; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/20/17 = 11:18 PM
*/
public class InitializedCreator {
public static void main(String[] args) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/InitializedCreator.java
import com.io.bio.file.FileUtils;
import java.io.IOException;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/20/17 = 11:18 PM
*/
public class InitializedCreator {
public static void main(String[] args) throws IOException { | String data = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/SQLColumnCreator.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/20/17 = 9:43 PM
*/
public class SQLColumnCreator {
public static void main(String[] args) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/SQLColumnCreator.java
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/20/17 = 9:43 PM
*/
public class SQLColumnCreator {
public static void main(String[] args) throws IOException { | String data = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/current/lock/LockTestMain.java | // Path: jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java
// public class SynchronizedShareLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
//
// private volatile Type nodeType = null;
// private AtomicInteger count;
// private Node headNode, tailNode;
// private Byte[] obj;
//
// public SynchronizedShareLock(){
// obj = new Byte[0];
// headNode = new Node();
// tailNode = new Node();
// headNode.setNextNode(tailNode);
// count = new AtomicInteger(0);
// }
//
// @Override
// public void lock() throws InterruptedException {
// writeLock();
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// acquire(-1);
// if(count.get() == 0){
// nodeType = null;
// }
// obj.notifyAll();
// }
// }
//
// public void readLock() throws InterruptedException {
// Node.Type type = Node.Type.SHARE;
// synchronized (obj){
// tryLock(type);
// }
// }
//
// public void writeLock() throws InterruptedException{
// Node.Type type = Node.Type.SINGLE;
// synchronized (obj){
// tryLock(type);
// }
// }
//
// public void tryLock(Type type) throws InterruptedException{
// addWaiter(type);
// for (;;){
// try {
// Node node = getFirstNode();
// if(!node.getThread().isAlive()){
// logger.warning(node.getThread().getName()+" dead");
// moveToNextNode(node);
// continue;
// }
// if(Thread.currentThread().equals(node.getThread())){
// if(nodeType == null) {
// nodeType = node.getType();
// moveToNextNode(node);
// acquire(1);
// break;
// }else if(isShare()
// && Node.Type.SHARE.equals(node.getType())){
// moveToNextNode(node);
// acquire(1);
// break;
// }
// }
// obj.wait();
// }catch (InterruptedException exception){
// logger.warning(Thread.currentThread().getName()+" has been interrupted");
// acquire(1);
// throw new InterruptedException(Thread.currentThread().getName()+" has been interrupted");
// }
// }
// }
//
// private void addWaiter(Node.Type type){
// tailNode.setThread(Thread.currentThread());
// tailNode.setType(type);
// Node newTailNode = new Node();
// tailNode.setNextNode(newTailNode);
// tailNode = newTailNode;
// }
//
// private void moveToNextNode(Node node){
// headNode.setNextNode(node.getNextNode());
// }
//
// private Node getFirstNode(){
// return headNode.getNextNode();
// }
//
// private boolean isShare(){
// return Node.Type.SHARE.equals(nodeType);
// }
//
// private void acquire(int i){
// for (;;){
// int c = count.get();
// if(count.compareAndSet(c, c+i)){
// break;
// }
// }
// }
// }
| import com.current.lock.v3.SynchronizedShareLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; | package com.current.lock;
/**
* Author Mr.Pro
* Date 9/6/17 = 8:55 PM
*/
public class LockTestMain {
static int sum = 0; | // Path: jdklib/src/main/java/com/current/lock/v3/SynchronizedShareLock.java
// public class SynchronizedShareLock implements Lock {
//
// private Logger logger = Logger.getLogger(SynchronizedShareLock.class.getName());
//
// private volatile Type nodeType = null;
// private AtomicInteger count;
// private Node headNode, tailNode;
// private Byte[] obj;
//
// public SynchronizedShareLock(){
// obj = new Byte[0];
// headNode = new Node();
// tailNode = new Node();
// headNode.setNextNode(tailNode);
// count = new AtomicInteger(0);
// }
//
// @Override
// public void lock() throws InterruptedException {
// writeLock();
// }
//
// @Override
// public void unlock() {
// synchronized (obj){
// acquire(-1);
// if(count.get() == 0){
// nodeType = null;
// }
// obj.notifyAll();
// }
// }
//
// public void readLock() throws InterruptedException {
// Node.Type type = Node.Type.SHARE;
// synchronized (obj){
// tryLock(type);
// }
// }
//
// public void writeLock() throws InterruptedException{
// Node.Type type = Node.Type.SINGLE;
// synchronized (obj){
// tryLock(type);
// }
// }
//
// public void tryLock(Type type) throws InterruptedException{
// addWaiter(type);
// for (;;){
// try {
// Node node = getFirstNode();
// if(!node.getThread().isAlive()){
// logger.warning(node.getThread().getName()+" dead");
// moveToNextNode(node);
// continue;
// }
// if(Thread.currentThread().equals(node.getThread())){
// if(nodeType == null) {
// nodeType = node.getType();
// moveToNextNode(node);
// acquire(1);
// break;
// }else if(isShare()
// && Node.Type.SHARE.equals(node.getType())){
// moveToNextNode(node);
// acquire(1);
// break;
// }
// }
// obj.wait();
// }catch (InterruptedException exception){
// logger.warning(Thread.currentThread().getName()+" has been interrupted");
// acquire(1);
// throw new InterruptedException(Thread.currentThread().getName()+" has been interrupted");
// }
// }
// }
//
// private void addWaiter(Node.Type type){
// tailNode.setThread(Thread.currentThread());
// tailNode.setType(type);
// Node newTailNode = new Node();
// tailNode.setNextNode(newTailNode);
// tailNode = newTailNode;
// }
//
// private void moveToNextNode(Node node){
// headNode.setNextNode(node.getNextNode());
// }
//
// private Node getFirstNode(){
// return headNode.getNextNode();
// }
//
// private boolean isShare(){
// return Node.Type.SHARE.equals(nodeType);
// }
//
// private void acquire(int i){
// for (;;){
// int c = count.get();
// if(count.compareAndSet(c, c+i)){
// break;
// }
// }
// }
// }
// Path: jdklib/src/main/java/com/current/lock/LockTestMain.java
import com.current.lock.v3.SynchronizedShareLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
package com.current.lock;
/**
* Author Mr.Pro
* Date 9/6/17 = 8:55 PM
*/
public class LockTestMain {
static int sum = 0; | static SynchronizedShareLock lock = new SynchronizedShareLock(); |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/VoCreator.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.Random; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/22/17 = 10:48 AM
*/
public class VoCreator {
public static void main(String args[]) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/VoCreator.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.io.bio.file.FileUtils;
import java.io.IOException;
import java.util.Random;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/22/17 = 10:48 AM
*/
public class VoCreator {
public static void main(String args[]) throws IOException { | String data = FileUtils.readFile("test.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/io/bio/file/coupang/EnumReader.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.File;
import java.io.IOException; | package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/28/17 = 2:13 PM
*/
public class EnumReader {
public static void main(String[] arg) throws IOException { | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/io/bio/file/coupang/EnumReader.java
import com.io.bio.file.FileUtils;
import java.io.File;
import java.io.IOException;
package com.io.bio.file.coupang;
/**
* Author Mr.Pro
* Date 9/28/17 = 2:13 PM
*/
public class EnumReader {
public static void main(String[] arg) throws IOException { | String data = FileUtils.readFile("mock.txt"); |
caoyj1991/Core-Java | jdklib/src/main/java/com/utils/entity/creator/EntityFactory.java | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
| import com.io.bio.file.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map; | }else{
pgName = pgName.trim().replace(".","/");
}
if (this.projectDir != null
&&this.projectDir.endsWith("/")){
this.projectDir = this.projectDir.substring(0, this.projectDir.length()-1);
}
String path = (!this.projectDir.equals("")?this.projectDir+"/":"")+pgName;
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
entities.forEach(input->{
try {
buildJavaFile(path, input);
} catch (IOException e) {
e.printStackTrace();
}
});
}
private void buildJavaFile(String path,SqlTranslator.Entity entity) throws IOException {
String className = entity.getClazzName().toUpperCase().substring(0,1)+entity.getClazzName().substring(1, entity.getClazzName().length());
String fileString = buildPackage();
fileString += "public class "+className+" {\n";
fileString += buildVariables(entity.getVariables());
fileString += "\n}\n"; | // Path: jdklib/src/main/java/com/io/bio/file/FileUtils.java
// public class FileUtils {
//
// public static String readFile(String filePath) throws IOException {
// File file = new File(filePath);
// if(!file.exists()){
// throw new NoSuchFileException("Can not find "+filePath);
// }
// FileReader fileReader = new FileReader(filePath);
// int c;
// StringBuffer text = new StringBuffer();
// while ((c=fileReader.read())!=-1){
// char cc = (char)c;
// text.append(cc);
// }
// return text.toString();
// }
//
// public static void write(String path, String fileName, String data) throws IOException {
// File dir = new File(path);
// if(!dir.exists()){
// dir.mkdirs();
// }
// File writeFile = new File(path+"/"+fileName);
// writeFile.createNewFile();
// OutputStream outputStream = new FileOutputStream(writeFile);
// outputStream.write(data.getBytes());
// outputStream.flush();
// outputStream.close();
// }
//
// public static void main(String[] arg) throws IOException {
// String temp = readFile("test.txt");
// String[] t = temp.split("\n");
// for (String line : t){
// System.out.println(line.split(" ")[2].split(";")[0].trim()+",");
// }
// }
// }
// Path: jdklib/src/main/java/com/utils/entity/creator/EntityFactory.java
import com.io.bio.file.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
}else{
pgName = pgName.trim().replace(".","/");
}
if (this.projectDir != null
&&this.projectDir.endsWith("/")){
this.projectDir = this.projectDir.substring(0, this.projectDir.length()-1);
}
String path = (!this.projectDir.equals("")?this.projectDir+"/":"")+pgName;
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
entities.forEach(input->{
try {
buildJavaFile(path, input);
} catch (IOException e) {
e.printStackTrace();
}
});
}
private void buildJavaFile(String path,SqlTranslator.Entity entity) throws IOException {
String className = entity.getClazzName().toUpperCase().substring(0,1)+entity.getClazzName().substring(1, entity.getClazzName().length());
String fileString = buildPackage();
fileString += "public class "+className+" {\n";
fileString += buildVariables(entity.getVariables());
fileString += "\n}\n"; | FileUtils.write(path, className+".java", fileString); |
mast-group/itemset-mining | itemset-miner/src/main/java/itemsetmining/eval/StatisticalItemsetMining.java | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
| import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SortedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import ca.pfv.spmf.tools.other_dataset_tools.FixTransactionDatabaseTool;
import itemsetmining.itemset.Itemset; | package itemsetmining.eval;
public class StatisticalItemsetMining {
private static final FixTransactionDatabaseTool dbTool = new FixTransactionDatabaseTool();
public static void main(final String[] args) throws IOException {
// MTV Parameters
final String[] datasets = new String[] { "plants", "mammals", "abstracts", "uganda", "retail" };
final double[] minSupps = new double[] { 0.05750265949, 0.1872659176, 0.01164144353, 0.001, 0.00011342755 }; // relative
final int[] minAbsSupps = new int[] { 2000, 500, 10, 125, 10 }; // absolute
for (int i = 0; i < datasets.length; i++) {
final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/Datasets/Succintly/" + datasets[i]
+ ".dat";
// final String saveFile =
// "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/MTV/" +
// datasets[i] + ".txt";
// mineMTVItemsets(new File(dbPath), minSupps[i], 200, new
// File(saveFile));
// mineSLIMItemsets(new File(dbPath), minAbsSupps[i], 24);
// mineKRIMPItemsets(new File(dbPath), minAbsSupps[i]);
// mineTilingItemsets(new File(dbPath), minSupps[i]); // min
// area
}
}
| // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
// Path: itemset-miner/src/main/java/itemsetmining/eval/StatisticalItemsetMining.java
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SortedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import ca.pfv.spmf.tools.other_dataset_tools.FixTransactionDatabaseTool;
import itemsetmining.itemset.Itemset;
package itemsetmining.eval;
public class StatisticalItemsetMining {
private static final FixTransactionDatabaseTool dbTool = new FixTransactionDatabaseTool();
public static void main(final String[] args) throws IOException {
// MTV Parameters
final String[] datasets = new String[] { "plants", "mammals", "abstracts", "uganda", "retail" };
final double[] minSupps = new double[] { 0.05750265949, 0.1872659176, 0.01164144353, 0.001, 0.00011342755 }; // relative
final int[] minAbsSupps = new int[] { 2000, 500, 10, 125, 10 }; // absolute
for (int i = 0; i < datasets.length; i++) {
final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/Datasets/Succintly/" + datasets[i]
+ ".dat";
// final String saveFile =
// "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/MTV/" +
// datasets[i] + ".txt";
// mineMTVItemsets(new File(dbPath), minSupps[i], 200, new
// File(saveFile));
// mineSLIMItemsets(new File(dbPath), minAbsSupps[i], 24);
// mineKRIMPItemsets(new File(dbPath), minAbsSupps[i]);
// mineTilingItemsets(new File(dbPath), minSupps[i]); // min
// area
}
}
| public static SortedMap<Itemset, Double> mineMTVItemsets(final File dbFile, final double minSup, |
mast-group/itemset-mining | itemset-miner/src/main/java/itemsetmining/itemset/ItemsetTree.java | // Path: itemset-miner/src/main/java/itemsetmining/util/MemoryLogger.java
// public class MemoryLogger {
//
// // the only instance of this class (this is the "singleton" design pattern)
// private static MemoryLogger instance = new MemoryLogger();
//
// // variable to store the maximum memory usage
// private double maxMemory = 0;
//
// /**
// * Method to obtain the only instance of this class
// *
// * @return instance of MemoryLogger
// */
// public static MemoryLogger getInstance() {
// return instance;
// }
//
// /**
// * To get the maximum amount of memory used until now
// *
// * @return a double value indicating memory as megabytes
// */
// public double getMaxMemory() {
// return maxMemory;
// }
//
// /**
// * Reset the maximum amount of memory recorded.
// */
// public void reset() {
// maxMemory = 0;
// }
//
// /**
// * Check the current memory usage and record it if it is higher than the
// * amount of memory previously recorded.
// */
// public void checkMemory() {
// final double currentMemory = (Runtime.getRuntime().totalMemory() - Runtime
// .getRuntime().freeMemory()) / 1024d / 1024d;
// if (currentMemory > maxMemory) {
// maxMemory = currentMemory;
// }
// }
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.google.common.collect.Multiset;
import itemsetmining.util.MemoryLogger; | // Randomly pick child to traverse proportional to its itemset support
double p = Math.random();
ItemsetTreeNode child = null;
for (final Map.Entry<ItemsetTreeNode, Integer> entry : supports.entrySet()) {
// final double childProb = 1. / node.children.size();
final double childProb = entry.getValue() / sumSupport;
if (p < childProb) {
child = entry.getKey();
} else {
p -= childProb;
}
}
assert child != null;
traverse(child, itemset);
}
/**
* Build the itemset-tree based on an input file containing transactions
*
* @param input
* an input file
* @return
*/
public void buildTree(final File inputFile) throws IOException {
// record start time
startTimestamp = System.currentTimeMillis();
// reset memory usage statistics | // Path: itemset-miner/src/main/java/itemsetmining/util/MemoryLogger.java
// public class MemoryLogger {
//
// // the only instance of this class (this is the "singleton" design pattern)
// private static MemoryLogger instance = new MemoryLogger();
//
// // variable to store the maximum memory usage
// private double maxMemory = 0;
//
// /**
// * Method to obtain the only instance of this class
// *
// * @return instance of MemoryLogger
// */
// public static MemoryLogger getInstance() {
// return instance;
// }
//
// /**
// * To get the maximum amount of memory used until now
// *
// * @return a double value indicating memory as megabytes
// */
// public double getMaxMemory() {
// return maxMemory;
// }
//
// /**
// * Reset the maximum amount of memory recorded.
// */
// public void reset() {
// maxMemory = 0;
// }
//
// /**
// * Check the current memory usage and record it if it is higher than the
// * amount of memory previously recorded.
// */
// public void checkMemory() {
// final double currentMemory = (Runtime.getRuntime().totalMemory() - Runtime
// .getRuntime().freeMemory()) / 1024d / 1024d;
// if (currentMemory > maxMemory) {
// maxMemory = currentMemory;
// }
// }
//
// }
// Path: itemset-miner/src/main/java/itemsetmining/itemset/ItemsetTree.java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.google.common.collect.Multiset;
import itemsetmining.util.MemoryLogger;
// Randomly pick child to traverse proportional to its itemset support
double p = Math.random();
ItemsetTreeNode child = null;
for (final Map.Entry<ItemsetTreeNode, Integer> entry : supports.entrySet()) {
// final double childProb = 1. / node.children.size();
final double childProb = entry.getValue() / sumSupport;
if (p < childProb) {
child = entry.getKey();
} else {
p -= childProb;
}
}
assert child != null;
traverse(child, itemset);
}
/**
* Build the itemset-tree based on an input file containing transactions
*
* @param input
* an input file
* @return
*/
public void buildTree(final File inputFile) throws IOException {
// record start time
startTimestamp = System.currentTimeMillis();
// reset memory usage statistics | MemoryLogger.getInstance().reset(); |
mast-group/itemset-mining | itemset-miner/src/main/java/itemsetmining/eval/CondensedFrequentItemsetMining.java | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import ca.pfv.spmf.algorithms.frequentpatterns.charm.AlgoCharmMFI;
import ca.pfv.spmf.algorithms.frequentpatterns.charm.AlgoCharm_Bitset;
import ca.pfv.spmf.input.transaction_database_list_integers.TransactionDatabase;
import ca.pfv.spmf.patterns.itemset_array_integers_with_tids_bitset.Itemsets;
import ca.pfv.spmf.tools.other_dataset_tools.FixTransactionDatabaseTool;
import itemsetmining.itemset.Itemset; | package itemsetmining.eval;
public class CondensedFrequentItemsetMining {
private static final FixTransactionDatabaseTool dbTool = new FixTransactionDatabaseTool();
public static void main(final String[] args) throws IOException {
// MTV Parameters
final String[] datasets = new String[] { "plants", "mammals", "abstracts", "uganda", "retail" };
final double[] minSupps = new double[] { 0.05750265949, 0.1872659176, 0.01164144353, 0.001, 0.00011342755 };
for (int i = 0; i < datasets.length; i++) {
final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/Datasets/Succintly/" + datasets[i]
+ ".dat";
final String saveFile = "/disk/data1/jfowkes/logs/" + datasets[i] + "-closed-fim.txt";
mineClosedFrequentItemsetsCharm(dbPath, saveFile, minSupps[i]);
}
}
/** Run Charm closed FIM algorithm */ | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
// Path: itemset-miner/src/main/java/itemsetmining/eval/CondensedFrequentItemsetMining.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Ordering;
import ca.pfv.spmf.algorithms.frequentpatterns.charm.AlgoCharmMFI;
import ca.pfv.spmf.algorithms.frequentpatterns.charm.AlgoCharm_Bitset;
import ca.pfv.spmf.input.transaction_database_list_integers.TransactionDatabase;
import ca.pfv.spmf.patterns.itemset_array_integers_with_tids_bitset.Itemsets;
import ca.pfv.spmf.tools.other_dataset_tools.FixTransactionDatabaseTool;
import itemsetmining.itemset.Itemset;
package itemsetmining.eval;
public class CondensedFrequentItemsetMining {
private static final FixTransactionDatabaseTool dbTool = new FixTransactionDatabaseTool();
public static void main(final String[] args) throws IOException {
// MTV Parameters
final String[] datasets = new String[] { "plants", "mammals", "abstracts", "uganda", "retail" };
final double[] minSupps = new double[] { 0.05750265949, 0.1872659176, 0.01164144353, 0.001, 0.00011342755 };
for (int i = 0; i < datasets.length; i++) {
final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Itemsets/Datasets/Succintly/" + datasets[i]
+ ".dat";
final String saveFile = "/disk/data1/jfowkes/logs/" + datasets[i] + "-closed-fim.txt";
mineClosedFrequentItemsetsCharm(dbPath, saveFile, minSupps[i]);
}
}
/** Run Charm closed FIM algorithm */ | public static SortedMap<Itemset, Integer> mineClosedFrequentItemsetsCharm(final String dataset, |
mast-group/itemset-mining | itemset-miner/src/test/java/itemsetmining/transaction/TransactionTest.java | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
| import static org.junit.Assert.assertTrue;
import itemsetmining.itemset.Itemset;
import java.util.HashMap;
import org.junit.Test; | package itemsetmining.transaction;
public class TransactionTest {
@Test
public void testBackgroundItemsets() {
| // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
// Path: itemset-miner/src/test/java/itemsetmining/transaction/TransactionTest.java
import static org.junit.Assert.assertTrue;
import itemsetmining.itemset.Itemset;
import java.util.HashMap;
import org.junit.Test;
package itemsetmining.transaction;
public class TransactionTest {
@Test
public void testBackgroundItemsets() {
| final HashMap<Itemset, Double> itemsets = TransactionGenerator |
mast-group/itemset-mining | itemset-miner/src/main/java/itemsetmining/transaction/TransactionGenerator.java | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
| import itemsetmining.itemset.Itemset;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.apache.commons.io.LineIterator;
import org.apache.commons.math3.distribution.GeometricDistribution;
import org.apache.commons.math3.distribution.LogNormalDistribution;
import org.apache.commons.math3.distribution.UniformIntegerDistribution;
import org.apache.commons.math3.random.Well19937c;
import com.google.common.collect.Maps; | package itemsetmining.transaction;
public class TransactionGenerator {
private static final boolean VERBOSE = false;
/**
* Create interesting itemsets that highlight problems
*
* @param difficultyLevel
* An integer between 0 and 10
*
* @param noInstances
* The number of example itemset instances
*/ | // Path: itemset-miner/src/main/java/itemsetmining/itemset/Itemset.java
// public class Itemset extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 4667217256957834826L;
//
// /**
// * Constructor
// */
// public Itemset() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the new itemset
// */
// public Itemset(final Collection<Integer> items) {
// this.items = new BitSet(items.size());
// addAll(items);
// }
//
// /**
// * Constructor
// *
// * @param items
// * an array of items that should be added to the new itemset
// */
// public Itemset(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
// Path: itemset-miner/src/main/java/itemsetmining/transaction/TransactionGenerator.java
import itemsetmining.itemset.Itemset;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.apache.commons.io.LineIterator;
import org.apache.commons.math3.distribution.GeometricDistribution;
import org.apache.commons.math3.distribution.LogNormalDistribution;
import org.apache.commons.math3.distribution.UniformIntegerDistribution;
import org.apache.commons.math3.random.Well19937c;
import com.google.common.collect.Maps;
package itemsetmining.transaction;
public class TransactionGenerator {
private static final boolean VERBOSE = false;
/**
* Create interesting itemsets that highlight problems
*
* @param difficultyLevel
* An integer between 0 and 10
*
* @param noInstances
* The number of example itemset instances
*/ | public static HashMap<Itemset, Double> generateExampleItemsets( |
mast-group/itemset-mining | itemset-miner/src/test/java/itemsetmining/itemset/BitSetIteratorTest.java | // Path: itemset-miner/src/main/java/itemsetmining/transaction/Transaction.java
// public class Transaction extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 3327396055332538091L;
//
// /** Cached itemsets for this transaction */
// private HashMap<Itemset, Double> cachedItemsets;
//
// /** Cached covering for this transaction */
// private HashSet<Itemset> cachedCovering;
// private HashSet<Itemset> tempCachedCovering;
//
// public void initializeCachedItemsets(final Multiset<Integer> singletons,
// final long noTransactions) {
// cachedItemsets = new HashMap<>();
// for (final Multiset.Entry<Integer> entry : singletons.entrySet()) {
// if (this.contains(entry.getElement()))
// cachedItemsets.put(new Itemset(entry.getElement()),
// entry.getCount() / (double) noTransactions);
// }
// }
//
// public HashMap<Itemset, Double> getCachedItemsets() {
// return cachedItemsets;
// }
//
// public void addItemsetCache(final Itemset candidate, final double prob) {
// cachedItemsets.put(candidate, prob);
// }
//
// public void removeItemsetCache(final Itemset candidate) {
// cachedItemsets.remove(candidate);
// }
//
// public void updateCachedItemsets(final Map<Itemset, Double> newItemsets) {
// for (final Iterator<Entry<Itemset, Double>> it = cachedItemsets
// .entrySet().iterator(); it.hasNext();) {
// final Entry<Itemset, Double> entry = it.next();
// final Double newProb = newItemsets.get(entry.getKey());
// if (newProb != null)
// entry.setValue(newProb);
// else
// it.remove();
// }
// }
//
// /** Get cost of cached covering for hard EM-step */
// public double getCachedCost() {
// double totalCost = 0;
// for (final Entry<Itemset, Double> entry : cachedItemsets.entrySet()) {
// if (cachedCovering.contains(entry.getKey()))
// totalCost += -Math.log(entry.getValue());
// else
// totalCost += -Math.log(1 - entry.getValue());
// }
// return totalCost;
// }
//
// /** Get cost of cached covering for structural EM-step */
// public double getCachedCost(final Map<Itemset, Double> itemsets) {
// return calculateCachedCost(itemsets, cachedCovering);
// }
//
// /** Get cost of temp. cached covering for structural EM-step */
// public double getTempCachedCost(final Map<Itemset, Double> itemsets) {
// return calculateCachedCost(itemsets, tempCachedCovering);
// }
//
// /** Calculate cached cost for structural EM-step */
// private double calculateCachedCost(final Map<Itemset, Double> itemsets,
// final HashSet<Itemset> covering) {
// double totalCost = 0;
// for (final Entry<Itemset, Double> entry : cachedItemsets.entrySet()) {
// final Itemset set = entry.getKey();
// final Double prob = itemsets.get(set);
// if (prob != null) {
// if (covering.contains(set))
// totalCost += -Math.log(prob);
// else
// totalCost += -Math.log(1 - prob);
// }
// }
// return totalCost;
// }
//
// public void setCachedCovering(final HashSet<Itemset> covering) {
// cachedCovering = covering;
// }
//
// public HashSet<Itemset> getCachedCovering() {
// return cachedCovering;
// }
//
// public void setTempCachedCovering(final HashSet<Itemset> covering) {
// tempCachedCovering = covering;
// }
//
// public HashSet<Itemset> getTempCachedCovering() {
// return tempCachedCovering;
// }
//
// /**
// * Constructor
// */
// public Transaction() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the transaction
// */
// public Transaction(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import itemsetmining.transaction.Transaction;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.Lists; | package itemsetmining.itemset;
public class BitSetIteratorTest {
@Test
public void testIterator() {
| // Path: itemset-miner/src/main/java/itemsetmining/transaction/Transaction.java
// public class Transaction extends AbstractItemset implements Serializable {
// private static final long serialVersionUID = 3327396055332538091L;
//
// /** Cached itemsets for this transaction */
// private HashMap<Itemset, Double> cachedItemsets;
//
// /** Cached covering for this transaction */
// private HashSet<Itemset> cachedCovering;
// private HashSet<Itemset> tempCachedCovering;
//
// public void initializeCachedItemsets(final Multiset<Integer> singletons,
// final long noTransactions) {
// cachedItemsets = new HashMap<>();
// for (final Multiset.Entry<Integer> entry : singletons.entrySet()) {
// if (this.contains(entry.getElement()))
// cachedItemsets.put(new Itemset(entry.getElement()),
// entry.getCount() / (double) noTransactions);
// }
// }
//
// public HashMap<Itemset, Double> getCachedItemsets() {
// return cachedItemsets;
// }
//
// public void addItemsetCache(final Itemset candidate, final double prob) {
// cachedItemsets.put(candidate, prob);
// }
//
// public void removeItemsetCache(final Itemset candidate) {
// cachedItemsets.remove(candidate);
// }
//
// public void updateCachedItemsets(final Map<Itemset, Double> newItemsets) {
// for (final Iterator<Entry<Itemset, Double>> it = cachedItemsets
// .entrySet().iterator(); it.hasNext();) {
// final Entry<Itemset, Double> entry = it.next();
// final Double newProb = newItemsets.get(entry.getKey());
// if (newProb != null)
// entry.setValue(newProb);
// else
// it.remove();
// }
// }
//
// /** Get cost of cached covering for hard EM-step */
// public double getCachedCost() {
// double totalCost = 0;
// for (final Entry<Itemset, Double> entry : cachedItemsets.entrySet()) {
// if (cachedCovering.contains(entry.getKey()))
// totalCost += -Math.log(entry.getValue());
// else
// totalCost += -Math.log(1 - entry.getValue());
// }
// return totalCost;
// }
//
// /** Get cost of cached covering for structural EM-step */
// public double getCachedCost(final Map<Itemset, Double> itemsets) {
// return calculateCachedCost(itemsets, cachedCovering);
// }
//
// /** Get cost of temp. cached covering for structural EM-step */
// public double getTempCachedCost(final Map<Itemset, Double> itemsets) {
// return calculateCachedCost(itemsets, tempCachedCovering);
// }
//
// /** Calculate cached cost for structural EM-step */
// private double calculateCachedCost(final Map<Itemset, Double> itemsets,
// final HashSet<Itemset> covering) {
// double totalCost = 0;
// for (final Entry<Itemset, Double> entry : cachedItemsets.entrySet()) {
// final Itemset set = entry.getKey();
// final Double prob = itemsets.get(set);
// if (prob != null) {
// if (covering.contains(set))
// totalCost += -Math.log(prob);
// else
// totalCost += -Math.log(1 - prob);
// }
// }
// return totalCost;
// }
//
// public void setCachedCovering(final HashSet<Itemset> covering) {
// cachedCovering = covering;
// }
//
// public HashSet<Itemset> getCachedCovering() {
// return cachedCovering;
// }
//
// public void setTempCachedCovering(final HashSet<Itemset> covering) {
// tempCachedCovering = covering;
// }
//
// public HashSet<Itemset> getTempCachedCovering() {
// return tempCachedCovering;
// }
//
// /**
// * Constructor
// */
// public Transaction() {
// this.items = new BitSet();
// }
//
// /**
// * Constructor
// *
// * @param items
// * a collection of items that should be added to the transaction
// */
// public Transaction(final int... items) {
// this.items = new BitSet(items.length);
// add(items);
// }
//
// }
// Path: itemset-miner/src/test/java/itemsetmining/itemset/BitSetIteratorTest.java
import static org.junit.Assert.assertEquals;
import itemsetmining.transaction.Transaction;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.Lists;
package itemsetmining.itemset;
public class BitSetIteratorTest {
@Test
public void testIterator() {
| final Transaction transaction = new Transaction(1, 2, 3, 4); |
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRAClient.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandler.java
// public class IssueHandler {
// protected Selenium selenium = JIRAClient.selenium;
//
// public void update() {
// selenium.click("Update");
// }
//
// public void resolve() {
// selenium.click("link=Resolve Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolve issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolved");
// }
// public void close() {
// selenium.click("link=Close Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Close Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Closed");
// }
// public void reopen() {
// selenium.click("link=Reopen Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopen Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopened");
// }
//
// public void attachFile() {
// selenium.click("//a[@id='opsbar-operations_more']/span");
// selenium.click("attach-file");
// }
//
// public void editIssue() {
// selenium.click("editIssue");
// selenium.waitForPageToLoad("3000");
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandlerProvider.java
// public abstract class IssueHandlerProvider {
// public static IssueHandler getIssueHandler() {
// String jiraVersion = System.getProperty("jira.deploy.version");
//
// if(jiraVersion == null || jiraVersion.equals("4.2.2-b589")) {
// return new IssueHandlerJIRA42OrLater();
// } else if(jiraVersion.equals("4.1.1")) {
// return new IssueHandlerJIRA41OrLater();
// } else {
// return new IssueHandler();
// }
// }
// }
| import java.net.URL;
import org.agilos.jira.soapclient.JiraSoapService;
import org.agilos.jira.soapclient.JiraSoapServiceService;
import org.agilos.jira.soapclient.JiraSoapServiceServiceLocator;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandler;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandlerProvider;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.Selenium;
| package org.agilos.zendesk_jira_plugin.testframework;
/**
* Wraps the implementation details of how to connect to JIRA and login.
*
* This is a Singleton, so use the {@link #instance} method to get an instance to the concrete instance.
*
* The following system properties define the behavior of the <code>JIRAClient</code>:
* <ul>
* <li> zendesk.jira.url The url of the JIRA instance the client should connect to
* <li> zendesk.jira.login.name The user name to login with
* <li> zendesk.jira.login.password The password to login to jira with
* </ul>
*/
public class JIRAClient {
private static JIRAClient instance = new JIRAClient();
protected JiraSoapService jiraSoapService;
protected String jiraSoapToken;
| // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandler.java
// public class IssueHandler {
// protected Selenium selenium = JIRAClient.selenium;
//
// public void update() {
// selenium.click("Update");
// }
//
// public void resolve() {
// selenium.click("link=Resolve Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolve issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolved");
// }
// public void close() {
// selenium.click("link=Close Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Close Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Closed");
// }
// public void reopen() {
// selenium.click("link=Reopen Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopen Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopened");
// }
//
// public void attachFile() {
// selenium.click("//a[@id='opsbar-operations_more']/span");
// selenium.click("attach-file");
// }
//
// public void editIssue() {
// selenium.click("editIssue");
// selenium.waitForPageToLoad("3000");
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandlerProvider.java
// public abstract class IssueHandlerProvider {
// public static IssueHandler getIssueHandler() {
// String jiraVersion = System.getProperty("jira.deploy.version");
//
// if(jiraVersion == null || jiraVersion.equals("4.2.2-b589")) {
// return new IssueHandlerJIRA42OrLater();
// } else if(jiraVersion.equals("4.1.1")) {
// return new IssueHandlerJIRA41OrLater();
// } else {
// return new IssueHandler();
// }
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRAClient.java
import java.net.URL;
import org.agilos.jira.soapclient.JiraSoapService;
import org.agilos.jira.soapclient.JiraSoapServiceService;
import org.agilos.jira.soapclient.JiraSoapServiceServiceLocator;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandler;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandlerProvider;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.Selenium;
package org.agilos.zendesk_jira_plugin.testframework;
/**
* Wraps the implementation details of how to connect to JIRA and login.
*
* This is a Singleton, so use the {@link #instance} method to get an instance to the concrete instance.
*
* The following system properties define the behavior of the <code>JIRAClient</code>:
* <ul>
* <li> zendesk.jira.url The url of the JIRA instance the client should connect to
* <li> zendesk.jira.login.name The user name to login with
* <li> zendesk.jira.login.password The password to login to jira with
* </ul>
*/
public class JIRAClient {
private static JIRAClient instance = new JIRAClient();
protected JiraSoapService jiraSoapService;
protected String jiraSoapToken;
| public static IssueHandler issueHandler = IssueHandlerProvider.getIssueHandler();
|
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRAClient.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandler.java
// public class IssueHandler {
// protected Selenium selenium = JIRAClient.selenium;
//
// public void update() {
// selenium.click("Update");
// }
//
// public void resolve() {
// selenium.click("link=Resolve Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolve issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolved");
// }
// public void close() {
// selenium.click("link=Close Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Close Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Closed");
// }
// public void reopen() {
// selenium.click("link=Reopen Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopen Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopened");
// }
//
// public void attachFile() {
// selenium.click("//a[@id='opsbar-operations_more']/span");
// selenium.click("attach-file");
// }
//
// public void editIssue() {
// selenium.click("editIssue");
// selenium.waitForPageToLoad("3000");
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandlerProvider.java
// public abstract class IssueHandlerProvider {
// public static IssueHandler getIssueHandler() {
// String jiraVersion = System.getProperty("jira.deploy.version");
//
// if(jiraVersion == null || jiraVersion.equals("4.2.2-b589")) {
// return new IssueHandlerJIRA42OrLater();
// } else if(jiraVersion.equals("4.1.1")) {
// return new IssueHandlerJIRA41OrLater();
// } else {
// return new IssueHandler();
// }
// }
// }
| import java.net.URL;
import org.agilos.jira.soapclient.JiraSoapService;
import org.agilos.jira.soapclient.JiraSoapServiceService;
import org.agilos.jira.soapclient.JiraSoapServiceServiceLocator;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandler;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandlerProvider;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.Selenium;
| package org.agilos.zendesk_jira_plugin.testframework;
/**
* Wraps the implementation details of how to connect to JIRA and login.
*
* This is a Singleton, so use the {@link #instance} method to get an instance to the concrete instance.
*
* The following system properties define the behavior of the <code>JIRAClient</code>:
* <ul>
* <li> zendesk.jira.url The url of the JIRA instance the client should connect to
* <li> zendesk.jira.login.name The user name to login with
* <li> zendesk.jira.login.password The password to login to jira with
* </ul>
*/
public class JIRAClient {
private static JIRAClient instance = new JIRAClient();
protected JiraSoapService jiraSoapService;
protected String jiraSoapToken;
| // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandler.java
// public class IssueHandler {
// protected Selenium selenium = JIRAClient.selenium;
//
// public void update() {
// selenium.click("Update");
// }
//
// public void resolve() {
// selenium.click("link=Resolve Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolve issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Resolved");
// }
// public void close() {
// selenium.click("link=Close Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Close Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Closed");
// }
// public void reopen() {
// selenium.click("link=Reopen Issue");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopen Issue");
// selenium.click("issue-workflow-transition-submit");
// selenium.waitForPageToLoad("3000");
// selenium.isTextPresent("Reopened");
// }
//
// public void attachFile() {
// selenium.click("//a[@id='opsbar-operations_more']/span");
// selenium.click("attach-file");
// }
//
// public void editIssue() {
// selenium.click("editIssue");
// selenium.waitForPageToLoad("3000");
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/framework/issuehandler/IssueHandlerProvider.java
// public abstract class IssueHandlerProvider {
// public static IssueHandler getIssueHandler() {
// String jiraVersion = System.getProperty("jira.deploy.version");
//
// if(jiraVersion == null || jiraVersion.equals("4.2.2-b589")) {
// return new IssueHandlerJIRA42OrLater();
// } else if(jiraVersion.equals("4.1.1")) {
// return new IssueHandlerJIRA41OrLater();
// } else {
// return new IssueHandler();
// }
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRAClient.java
import java.net.URL;
import org.agilos.jira.soapclient.JiraSoapService;
import org.agilos.jira.soapclient.JiraSoapServiceService;
import org.agilos.jira.soapclient.JiraSoapServiceServiceLocator;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandler;
import org.agilos.zendesk_jira_plugin.integrationtest.framework.issuehandler.IssueHandlerProvider;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.Selenium;
package org.agilos.zendesk_jira_plugin.testframework;
/**
* Wraps the implementation details of how to connect to JIRA and login.
*
* This is a Singleton, so use the {@link #instance} method to get an instance to the concrete instance.
*
* The following system properties define the behavior of the <code>JIRAClient</code>:
* <ul>
* <li> zendesk.jira.url The url of the JIRA instance the client should connect to
* <li> zendesk.jira.login.name The user name to login with
* <li> zendesk.jira.login.password The password to login to jira with
* </ul>
*/
public class JIRAClient {
private static JIRAClient instance = new JIRAClient();
protected JiraSoapService jiraSoapService;
protected String jiraSoapToken;
| public static IssueHandler issueHandler = IssueHandlerProvider.getIssueHandler();
|
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskServerStub.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/notifications/NotificationListener.java
// public class NotificationListener extends Application {
// private Logger log = Logger.getLogger(NotificationListener.class.getName());
// private final LinkedBlockingQueue<Request> notificationQueue;
//
// public NotificationListener(LinkedBlockingQueue<Request> notificationQueuecontext) {
// super();
// this.notificationQueue = notificationQueuecontext;
// createRoot();
// }
//
// @Override
// public synchronized Restlet createRoot() {
// // Create a router Restlet that routes each call to a
// // new instance of the NotificationHandler.
//
// Router router = new Router(getContext());
//
// // Defines only one route
// log.debug("Attaching handler ");
// router.attachDefault(new NotificationHandler());
//
// Guard guard = new Guard(getContext(), ChallengeScheme.HTTP_BASIC, "Tutorial");
// guard.getSecrets().put("jira", "jira".toCharArray());
// guard.setNext(router);
//
// return guard;
// }
//
// public class NotificationHandler extends Restlet {
// @Override
// public void handle(Request request, Response response) {
// log.info("Received request to "+request.getResourceRef()+" from " +request.getHostRef()+ " with method: " + request.getMethod() +" and entity "+request.getEntityAsText());
// try {
// notificationQueue.put(request);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// response.setStatus(Status.SUCCESS_OK);
// }
// }
// }
| import java.util.concurrent.LinkedBlockingQueue;
import org.agilos.zendesk_jira_plugin.integrationtest.notifications.NotificationListener;
import org.restlet.Component;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
| package org.agilos.zendesk_jira_plugin.testframework;
public class ZendeskServerStub extends Component {
//private Logger log = Logger.getLogger(ZendeskServerStub.class.getName());
public ZendeskServerStub(LinkedBlockingQueue<Request> notificationQueue, int port) {
super();
// Add a new HTTP server listening on the specific port.
getServers().add(Protocol.HTTP, port);
| // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/notifications/NotificationListener.java
// public class NotificationListener extends Application {
// private Logger log = Logger.getLogger(NotificationListener.class.getName());
// private final LinkedBlockingQueue<Request> notificationQueue;
//
// public NotificationListener(LinkedBlockingQueue<Request> notificationQueuecontext) {
// super();
// this.notificationQueue = notificationQueuecontext;
// createRoot();
// }
//
// @Override
// public synchronized Restlet createRoot() {
// // Create a router Restlet that routes each call to a
// // new instance of the NotificationHandler.
//
// Router router = new Router(getContext());
//
// // Defines only one route
// log.debug("Attaching handler ");
// router.attachDefault(new NotificationHandler());
//
// Guard guard = new Guard(getContext(), ChallengeScheme.HTTP_BASIC, "Tutorial");
// guard.getSecrets().put("jira", "jira".toCharArray());
// guard.setNext(router);
//
// return guard;
// }
//
// public class NotificationHandler extends Restlet {
// @Override
// public void handle(Request request, Response response) {
// log.info("Received request to "+request.getResourceRef()+" from " +request.getHostRef()+ " with method: " + request.getMethod() +" and entity "+request.getEntityAsText());
// try {
// notificationQueue.put(request);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// response.setStatus(Status.SUCCESS_OK);
// }
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskServerStub.java
import java.util.concurrent.LinkedBlockingQueue;
import org.agilos.zendesk_jira_plugin.integrationtest.notifications.NotificationListener;
import org.restlet.Component;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
package org.agilos.zendesk_jira_plugin.testframework;
public class ZendeskServerStub extends Component {
//private Logger log = Logger.getLogger(ZendeskServerStub.class.getName());
public ZendeskServerStub(LinkedBlockingQueue<Request> notificationQueue, int port) {
super();
// Add a new HTTP server listening on the specific port.
getServers().add(Protocol.HTTP, port);
| getDefaultHost().attach("/tickets", new NotificationListener(notificationQueue));
|
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/NotificationFixture.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskServerStub.java
// public class ZendeskServerStub extends Component {
//
// //private Logger log = Logger.getLogger(ZendeskServerStub.class.getName());
//
// public ZendeskServerStub(LinkedBlockingQueue<Request> notificationQueue, int port) {
// super();
// // Add a new HTTP server listening on the specific port.
// getServers().add(Protocol.HTTP, port);
//
// getDefaultHost().attach("/tickets", new NotificationListener(notificationQueue));
// getDefaultHost().attach("/uploads.xml", new AttachmentListener());
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.agilos.jira.soapclient.RemoteComment;
import org.agilos.jira.soapclient.RemoteCustomFieldValue;
import org.agilos.jira.soapclient.RemoteFieldValue;
import org.agilos.jira.soapclient.RemoteIssue;
import org.agilos.jira.soapclient.RemoteProject;
import org.agilos.zendesk_jira_plugin.testframework.ZendeskServerStub;
import org.apache.log4j.Logger;
import org.restlet.data.Request;
import com.atlassian.jira.issue.IssueFieldConstants;
| package org.agilos.zendesk_jira_plugin.integrationtest.fixtures;
public class NotificationFixture extends JIRAFixture {
private static final Logger log = Logger.getLogger(NotificationFixture.class.getName());
private String ticketID ="215";
protected static LinkedBlockingQueue<Request> httpNotificationQueue = new LinkedBlockingQueue<Request>();
protected static LinkedBlockingQueue<Request> httpsNotificationQueue= new LinkedBlockingQueue<Request>();
| // Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskServerStub.java
// public class ZendeskServerStub extends Component {
//
// //private Logger log = Logger.getLogger(ZendeskServerStub.class.getName());
//
// public ZendeskServerStub(LinkedBlockingQueue<Request> notificationQueue, int port) {
// super();
// // Add a new HTTP server listening on the specific port.
// getServers().add(Protocol.HTTP, port);
//
// getDefaultHost().attach("/tickets", new NotificationListener(notificationQueue));
// getDefaultHost().attach("/uploads.xml", new AttachmentListener());
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/NotificationFixture.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.agilos.jira.soapclient.RemoteComment;
import org.agilos.jira.soapclient.RemoteCustomFieldValue;
import org.agilos.jira.soapclient.RemoteFieldValue;
import org.agilos.jira.soapclient.RemoteIssue;
import org.agilos.jira.soapclient.RemoteProject;
import org.agilos.zendesk_jira_plugin.testframework.ZendeskServerStub;
import org.apache.log4j.Logger;
import org.restlet.data.Request;
import com.atlassian.jira.issue.IssueFieldConstants;
package org.agilos.zendesk_jira_plugin.integrationtest.fixtures;
public class NotificationFixture extends JIRAFixture {
private static final Logger log = Logger.getLogger(NotificationFixture.class.getName());
private String ticketID ="215";
protected static LinkedBlockingQueue<Request> httpNotificationQueue = new LinkedBlockingQueue<Request>();
protected static LinkedBlockingQueue<Request> httpsNotificationQueue= new LinkedBlockingQueue<Request>();
| private static final ZendeskServerStub httpServer = new ZendeskServerStub(httpNotificationQueue, 8182);
|
zendesk/zendesk-jira-plugin | src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/testcases/NotificationTest.java | // Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/AbstractNotificationTest.java
// public abstract class AbstractNotificationTest extends JIRATest {
// public NotificationFixture fixture;
// protected String issueKey;
//
// private Logger log = Logger.getLogger(NotificationTest.class.getName());
//
// @BeforeMethod (alwaysRun = true)
// @Override
// protected void setUpTest() throws Exception {
// super.setUpTest();
// issueKey = fixture.createIssue(PROJECT_KEY).getKey();
// }
//
// @AfterMethod (alwaysRun = true)
// protected void tearDownTest() throws Exception {
// Request request = fixture.getNextRequestInstant();
// if (request != null) log.warn("Notification remains on message queue after testcase has finish" + request.getEntityAsText());
// }
//
// @Override
// protected JIRAFixture getFixture() {
// if (fixture == null ) fixture = new NotificationFixture();
// return fixture;
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/TestDataFactory.java
// public abstract class TestDataFactory {
// private static final Properties properties = loadProperties("testdata");;
//
// public static String getSoapResponse(String ID) {
// return (String)properties.get("soap_response."+ID);
// }
//
// private static Properties loadProperties(String name) {
// if (name == null)
// throw new IllegalArgumentException("null input: name");
//
// if (name.startsWith("/"))
// name = name.substring(1);
//
// if (name.endsWith(SUFFIX))
// name = name.substring(0, name.length() - SUFFIX.length());
//
// Properties result = null;
//
// InputStream in = null;
//
// try {
// name = name.replace('/', '.');
// // Throws MissingResourceException on lookup failures:
// final ResourceBundle rb = ResourceBundle.getBundle(name, Locale
// .getDefault(), ClassLoader.getSystemClassLoader());
//
// result = new Properties();
// for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
// final String key = (String) keys.nextElement();
// final String value = rb.getString(key);
//
// result.put(key, value);
// }
// } catch (Exception e) {
// result = null;
// } finally {
// if (in != null)
// try {
// in.close();
// } catch (Throwable ignore) {
// }
// }
//
// if (THROW_ON_LOAD_FAILURE && (result == null)) {
// throw new IllegalArgumentException("could not load ["+ name +"]");
// }
//
// return result;
// }
//
// private static final boolean THROW_ON_LOAD_FAILURE = true;
// private static final String SUFFIX = ".properties";
// }
| import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import it.org.agilos.zendesk_jira_plugin.integrationtest.AbstractNotificationTest;
import java.util.Calendar;
import org.agilos.jira.soapclient.RemoteComment;
import org.agilos.jira.soapclient.RemoteIssue;
import org.agilos.jira.soapclient.RemoteProject;
import org.agilos.zendesk_jira_plugin.testframework.TestDataFactory;
import org.apache.log4j.Logger;
import org.restlet.data.Parameter;
import org.restlet.engine.http.HttpConstants;
import org.restlet.engine.http.HttpRequest;
import org.restlet.util.Series;
import org.testng.annotations.Test;
| package it.org.agilos.zendesk_jira_plugin.integrationtest.testcases;
public class NotificationTest extends AbstractNotificationTest {
private static final Logger log = Logger.getLogger(NotificationTest.class.getName());
@Test (groups = {"regressionTests"} )
public void testCommentAddedNotification() throws Exception {
fixture.updateIssueWithComment(issueKey, "Test comment");
assertEquals("Wrong response received after changing comment",
| // Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/AbstractNotificationTest.java
// public abstract class AbstractNotificationTest extends JIRATest {
// public NotificationFixture fixture;
// protected String issueKey;
//
// private Logger log = Logger.getLogger(NotificationTest.class.getName());
//
// @BeforeMethod (alwaysRun = true)
// @Override
// protected void setUpTest() throws Exception {
// super.setUpTest();
// issueKey = fixture.createIssue(PROJECT_KEY).getKey();
// }
//
// @AfterMethod (alwaysRun = true)
// protected void tearDownTest() throws Exception {
// Request request = fixture.getNextRequestInstant();
// if (request != null) log.warn("Notification remains on message queue after testcase has finish" + request.getEntityAsText());
// }
//
// @Override
// protected JIRAFixture getFixture() {
// if (fixture == null ) fixture = new NotificationFixture();
// return fixture;
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/TestDataFactory.java
// public abstract class TestDataFactory {
// private static final Properties properties = loadProperties("testdata");;
//
// public static String getSoapResponse(String ID) {
// return (String)properties.get("soap_response."+ID);
// }
//
// private static Properties loadProperties(String name) {
// if (name == null)
// throw new IllegalArgumentException("null input: name");
//
// if (name.startsWith("/"))
// name = name.substring(1);
//
// if (name.endsWith(SUFFIX))
// name = name.substring(0, name.length() - SUFFIX.length());
//
// Properties result = null;
//
// InputStream in = null;
//
// try {
// name = name.replace('/', '.');
// // Throws MissingResourceException on lookup failures:
// final ResourceBundle rb = ResourceBundle.getBundle(name, Locale
// .getDefault(), ClassLoader.getSystemClassLoader());
//
// result = new Properties();
// for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
// final String key = (String) keys.nextElement();
// final String value = rb.getString(key);
//
// result.put(key, value);
// }
// } catch (Exception e) {
// result = null;
// } finally {
// if (in != null)
// try {
// in.close();
// } catch (Throwable ignore) {
// }
// }
//
// if (THROW_ON_LOAD_FAILURE && (result == null)) {
// throw new IllegalArgumentException("could not load ["+ name +"]");
// }
//
// return result;
// }
//
// private static final boolean THROW_ON_LOAD_FAILURE = true;
// private static final String SUFFIX = ".properties";
// }
// Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/testcases/NotificationTest.java
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import it.org.agilos.zendesk_jira_plugin.integrationtest.AbstractNotificationTest;
import java.util.Calendar;
import org.agilos.jira.soapclient.RemoteComment;
import org.agilos.jira.soapclient.RemoteIssue;
import org.agilos.jira.soapclient.RemoteProject;
import org.agilos.zendesk_jira_plugin.testframework.TestDataFactory;
import org.apache.log4j.Logger;
import org.restlet.data.Parameter;
import org.restlet.engine.http.HttpConstants;
import org.restlet.engine.http.HttpRequest;
import org.restlet.util.Series;
import org.testng.annotations.Test;
package it.org.agilos.zendesk_jira_plugin.integrationtest.testcases;
public class NotificationTest extends AbstractNotificationTest {
private static final Logger log = Logger.getLogger(NotificationTest.class.getName());
@Test (groups = {"regressionTests"} )
public void testCommentAddedNotification() throws Exception {
fixture.updateIssueWithComment(issueKey, "Test comment");
assertEquals("Wrong response received after changing comment",
| TestDataFactory.getSoapResponse("testCommentAddedNotification.1"),
|
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/testframework/AttachmentListener.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/notifications/AttachmentReceiver.java
// public class AttachmentReceiver extends Resource {
// private static Logger log = Logger.getLogger(AttachmentReceiver.class.getName());
//
// public static File ATTACHMENT_DIRECTORY = new File("target"+File.separator+"zendeskstub-attachments");
//
// /**
// * Constructor with parameters invoked every time a new request is routed to
// * this resource.
// *
// * @param context
// * The parent context.
// * @param request
// * The request to handle.
// * @param response
// * The response to return.
// */
// public AttachmentReceiver(Context context, Request request, Response response) {
// super(context, request, response);
//
// // This resource generates only HTML representations.
// getVariants().add(new Variant(MediaType.TEXT_HTML));
// }
//
// /**
// * Mandatory. Specifies that this resource supports POST requests.
// */
// public boolean allowPost() {
// return true;
// }
// @Override
// public void acceptRepresentation(Representation entity) {
//
// if (entity != null) {
// if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType(), true)) {
// Form query = getRequest().getResourceRef().getQueryAsForm();
// String attachmentName = query.getFirstValue("filename");
//
// InputStream inBuffer = null;
// OutputStream outBuffer = null;
//
// try{
// File attachmentFile = new File(ATTACHMENT_DIRECTORY+File.separator +attachmentName);
// FileOutputStream out = new FileOutputStream(attachmentFile);
//
// inBuffer = new BufferedInputStream(entity.getStream());
// outBuffer = new BufferedOutputStream(out);
//
// while(true){
// int bytedata = inBuffer.read();
// if(bytedata == -1)
// break;
// out.write(bytedata);
// }
// } catch (IOException e) {
// log.error("Failed to save attachment file to "+attachmentName, e);
// }
//
// finally{
// if(inBuffer != null)
// try {
// inBuffer.close();
// } catch (IOException e) {
// log.error("Failed to close atttachment inputBuffer",e);
// }
// if(outBuffer !=null)
// try {
// outBuffer.close();
// } catch (IOException e) {
// log.error("Failed to close atttachment outBuffer",e);
// }
// }
//
// Representation rep = new StringRepresentation("<uploads token=\"abc123\">\n"+
// "\t<attachments>\n"+
// "\t\t<attachment>789</attachment>\n"+
// "\t</attachments>\n"+
// "</uploads>", MediaType.TEXT_PLAIN);
// // Set the representation of the resource once the POST request has been handled.
// getResponse().setEntity(rep);
// // Set the status of the response.
// getResponse().setStatus(Status.SUCCESS_OK);
// } else {
// getResponse().setEntity(new StringRepresentation("Please use content type "+MediaType.APPLICATION_WWW_FORM,
// MediaType.TEXT_PLAIN));
// getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
// }
//
// } else {
// // POST request with no entity.
// getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
// }
// }
// }
| import org.agilos.zendesk_jira_plugin.integrationtest.notifications.AttachmentReceiver;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
| package org.agilos.zendesk_jira_plugin.testframework;
public class AttachmentListener extends Application {
/**
* Creates a unique route for all URIs to the sample resource
*/
@Override
public Restlet createRoot() {
Router router = new Router(getContext());
// All URIs are routed to a new instance of MyResource class.
| // Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/notifications/AttachmentReceiver.java
// public class AttachmentReceiver extends Resource {
// private static Logger log = Logger.getLogger(AttachmentReceiver.class.getName());
//
// public static File ATTACHMENT_DIRECTORY = new File("target"+File.separator+"zendeskstub-attachments");
//
// /**
// * Constructor with parameters invoked every time a new request is routed to
// * this resource.
// *
// * @param context
// * The parent context.
// * @param request
// * The request to handle.
// * @param response
// * The response to return.
// */
// public AttachmentReceiver(Context context, Request request, Response response) {
// super(context, request, response);
//
// // This resource generates only HTML representations.
// getVariants().add(new Variant(MediaType.TEXT_HTML));
// }
//
// /**
// * Mandatory. Specifies that this resource supports POST requests.
// */
// public boolean allowPost() {
// return true;
// }
// @Override
// public void acceptRepresentation(Representation entity) {
//
// if (entity != null) {
// if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType(), true)) {
// Form query = getRequest().getResourceRef().getQueryAsForm();
// String attachmentName = query.getFirstValue("filename");
//
// InputStream inBuffer = null;
// OutputStream outBuffer = null;
//
// try{
// File attachmentFile = new File(ATTACHMENT_DIRECTORY+File.separator +attachmentName);
// FileOutputStream out = new FileOutputStream(attachmentFile);
//
// inBuffer = new BufferedInputStream(entity.getStream());
// outBuffer = new BufferedOutputStream(out);
//
// while(true){
// int bytedata = inBuffer.read();
// if(bytedata == -1)
// break;
// out.write(bytedata);
// }
// } catch (IOException e) {
// log.error("Failed to save attachment file to "+attachmentName, e);
// }
//
// finally{
// if(inBuffer != null)
// try {
// inBuffer.close();
// } catch (IOException e) {
// log.error("Failed to close atttachment inputBuffer",e);
// }
// if(outBuffer !=null)
// try {
// outBuffer.close();
// } catch (IOException e) {
// log.error("Failed to close atttachment outBuffer",e);
// }
// }
//
// Representation rep = new StringRepresentation("<uploads token=\"abc123\">\n"+
// "\t<attachments>\n"+
// "\t\t<attachment>789</attachment>\n"+
// "\t</attachments>\n"+
// "</uploads>", MediaType.TEXT_PLAIN);
// // Set the representation of the resource once the POST request has been handled.
// getResponse().setEntity(rep);
// // Set the status of the response.
// getResponse().setStatus(Status.SUCCESS_OK);
// } else {
// getResponse().setEntity(new StringRepresentation("Please use content type "+MediaType.APPLICATION_WWW_FORM,
// MediaType.TEXT_PLAIN));
// getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
// }
//
// } else {
// // POST request with no entity.
// getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
// }
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/AttachmentListener.java
import org.agilos.zendesk_jira_plugin.integrationtest.notifications.AttachmentReceiver;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
package org.agilos.zendesk_jira_plugin.testframework;
public class AttachmentListener extends Application {
/**
* Creates a unique route for all URIs to the sample resource
*/
@Override
public Restlet createRoot() {
Router router = new Router(getContext());
// All URIs are routed to a new instance of MyResource class.
| router.attachDefault( AttachmentReceiver.class);
|
zendesk/zendesk-jira-plugin | src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/WebserviceFixture.java | // Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRARoles.java
// public abstract class JIRARoles {
// public static final String Administrators = "Administrators";
// public static final String Developers = "Developers";
// public static final String Users = "Users";
//
// public enum Roles { jiraadministrators, jiradevelopers, jirausers }//Define default groups
//
// private static Logger log = Logger.getLogger(JIRARoles.class.getName());
//
// private static final Map<String, RemoteProjectRole> roleMap = new HashMap<String, RemoteProjectRole>();
// private static JIRAClient jiraClient = JIRAClient.instance();
//
// public static RemoteProjectRole getRole(String name) {
// if (roleMap.isEmpty()) retrieveRoles();
// return roleMap.get(name);
// }
//
// public static void addUserToProjectRoleInProject(String userName, String projectRole, RemoteProject project) throws RemoteException, java.rmi.RemoteException {
// jiraClient.getService().addActorsToProjectRole(jiraClient.getToken(), new String[] { userName }, getRole(projectRole), project, "atlassian-user-role-actor");
// }
//
// public static void removeUserFromProjectRoleInProject(String username, String projectRole, RemoteProject project) throws RemoteException, java.rmi.RemoteException {
// jiraClient.getService().removeActorsFromProjectRole(jiraClient.getToken(), new String[] { username }, getRole(projectRole), project, "atlassian-user-role-actor");
// }
//
// /**
// * Always use this to add new roles, else the local roles cache will become obsolete
// */
// public static void addRole() {
// throw new NotImplementedException();
// }
//
// public static void retrieveRoles() {
// try {
// RemoteProjectRole[] roles = jiraClient.getService().getProjectRoles(jiraClient.getToken());
// for (int i=0;i<roles.length;i++) {
// roleMap.put(roles[i].getName(), roles[i]);
// }
// } catch (Exception e) {
// log.error("Unable to retieve project roles");
// }
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskWSClient.java
// public class ZendeskWSClient {
// private static AgilosSoapService agilosSoapService;
// private static String agilosSoapToken;
//
// public static AgilosSoapService getSoapService() {
// return agilosSoapService;
// }
//
// public static String getSoapToken() {
// return agilosSoapToken;
// }
//
// private Logger log = Logger.getLogger(ZendeskWSClient.class.getName());
//
// public ZendeskWSClient() throws ServiceException, RemoteException, MalformedURLException {
// AgilosSoapServiceService agilosSoapServiceGetter = new AgilosSoapServiceServiceLocator();
// URL agilosSOAPServiceUrl = new URL(JIRA.URL+"/rpc/soap/agilossoapservice-v1");
// log.debug("Retriving jira soap service from "+agilosSOAPServiceUrl);
// agilosSoapService = agilosSoapServiceGetter.getAgilossoapserviceV1(agilosSOAPServiceUrl);
// log.debug("Logging in with user: " + JIRA.LOGIN_NAME+" and password: " + JIRA.LOGIN_PASSWORD);
// agilosSoapToken = agilosSoapService.login(JIRA.LOGIN_NAME, JIRA.LOGIN_PASSWORD);
// }
//
// public RemoteUser[] assignableUsers(String projectKey) throws Exception {
// return agilosSoapService.getAssignableUsers(agilosSoapToken, projectKey);
// }
// }
| import org.agilos.jira.soapclient.RemoteUser;
import org.agilos.zendesk_jira_plugin.testframework.JIRARoles;
import org.agilos.zendesk_jira_plugin.testframework.ZendeskWSClient;
import org.apache.log4j.Logger; | package org.agilos.zendesk_jira_plugin.integrationtest.fixtures;
public class WebserviceFixture extends JIRAFixture {
protected ZendeskWSClient zendeskWSClient;
private Logger log = Logger.getLogger(WebserviceFixture.class.getName());
@Override
public void connect() throws Exception {
super.connect();
try {
zendeskWSClient = new ZendeskWSClient();
} catch (Exception e) {
log.error("Failed to create ZendeskWSClient", e);
}
}
public void assignUserToProject(String username, String projectKey) throws Exception {
log.info("Assigning user: "+username+" to project: "); | // Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/JIRARoles.java
// public abstract class JIRARoles {
// public static final String Administrators = "Administrators";
// public static final String Developers = "Developers";
// public static final String Users = "Users";
//
// public enum Roles { jiraadministrators, jiradevelopers, jirausers }//Define default groups
//
// private static Logger log = Logger.getLogger(JIRARoles.class.getName());
//
// private static final Map<String, RemoteProjectRole> roleMap = new HashMap<String, RemoteProjectRole>();
// private static JIRAClient jiraClient = JIRAClient.instance();
//
// public static RemoteProjectRole getRole(String name) {
// if (roleMap.isEmpty()) retrieveRoles();
// return roleMap.get(name);
// }
//
// public static void addUserToProjectRoleInProject(String userName, String projectRole, RemoteProject project) throws RemoteException, java.rmi.RemoteException {
// jiraClient.getService().addActorsToProjectRole(jiraClient.getToken(), new String[] { userName }, getRole(projectRole), project, "atlassian-user-role-actor");
// }
//
// public static void removeUserFromProjectRoleInProject(String username, String projectRole, RemoteProject project) throws RemoteException, java.rmi.RemoteException {
// jiraClient.getService().removeActorsFromProjectRole(jiraClient.getToken(), new String[] { username }, getRole(projectRole), project, "atlassian-user-role-actor");
// }
//
// /**
// * Always use this to add new roles, else the local roles cache will become obsolete
// */
// public static void addRole() {
// throw new NotImplementedException();
// }
//
// public static void retrieveRoles() {
// try {
// RemoteProjectRole[] roles = jiraClient.getService().getProjectRoles(jiraClient.getToken());
// for (int i=0;i<roles.length;i++) {
// roleMap.put(roles[i].getName(), roles[i]);
// }
// } catch (Exception e) {
// log.error("Unable to retieve project roles");
// }
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/ZendeskWSClient.java
// public class ZendeskWSClient {
// private static AgilosSoapService agilosSoapService;
// private static String agilosSoapToken;
//
// public static AgilosSoapService getSoapService() {
// return agilosSoapService;
// }
//
// public static String getSoapToken() {
// return agilosSoapToken;
// }
//
// private Logger log = Logger.getLogger(ZendeskWSClient.class.getName());
//
// public ZendeskWSClient() throws ServiceException, RemoteException, MalformedURLException {
// AgilosSoapServiceService agilosSoapServiceGetter = new AgilosSoapServiceServiceLocator();
// URL agilosSOAPServiceUrl = new URL(JIRA.URL+"/rpc/soap/agilossoapservice-v1");
// log.debug("Retriving jira soap service from "+agilosSOAPServiceUrl);
// agilosSoapService = agilosSoapServiceGetter.getAgilossoapserviceV1(agilosSOAPServiceUrl);
// log.debug("Logging in with user: " + JIRA.LOGIN_NAME+" and password: " + JIRA.LOGIN_PASSWORD);
// agilosSoapToken = agilosSoapService.login(JIRA.LOGIN_NAME, JIRA.LOGIN_PASSWORD);
// }
//
// public RemoteUser[] assignableUsers(String projectKey) throws Exception {
// return agilosSoapService.getAssignableUsers(agilosSoapToken, projectKey);
// }
// }
// Path: src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/WebserviceFixture.java
import org.agilos.jira.soapclient.RemoteUser;
import org.agilos.zendesk_jira_plugin.testframework.JIRARoles;
import org.agilos.zendesk_jira_plugin.testframework.ZendeskWSClient;
import org.apache.log4j.Logger;
package org.agilos.zendesk_jira_plugin.integrationtest.fixtures;
public class WebserviceFixture extends JIRAFixture {
protected ZendeskWSClient zendeskWSClient;
private Logger log = Logger.getLogger(WebserviceFixture.class.getName());
@Override
public void connect() throws Exception {
super.connect();
try {
zendeskWSClient = new ZendeskWSClient();
} catch (Exception e) {
log.error("Failed to create ZendeskWSClient", e);
}
}
public void assignUserToProject(String username, String projectKey) throws Exception {
log.info("Assigning user: "+username+" to project: "); | JIRARoles.addUserToProjectRoleInProject(username, JIRARoles.Developers, project); |
zendesk/zendesk-jira-plugin | src/main/java/org/agilos/jira/ws/AgilosSoapServiceImpl.java | // Path: src/main/java/org/agilos/jira/service/UserService.java
// public interface UserService {
//
// RemoteUser[] getAssignableUsers(String projectKey);
//
// }
| import com.atlassian.jira.rpc.auth.TokenManager;
import com.atlassian.jira.rpc.exception.RemoteAuthenticationException;
import com.atlassian.jira.rpc.exception.RemoteException;
import com.atlassian.jira.rpc.exception.RemotePermissionException;
import com.atlassian.jira.rpc.soap.beans.RemoteUser;
import com.opensymphony.user.User;
import org.agilos.jira.service.UserService;
import org.apache.log4j.Logger;
| package org.agilos.jira.ws;
public class AgilosSoapServiceImpl implements AgilosSoapService {
private TokenManager tokenManager; // The TokenManager functionality is very much inspired by the com.atlassian.jira.rpc.auth.TokenManager
| // Path: src/main/java/org/agilos/jira/service/UserService.java
// public interface UserService {
//
// RemoteUser[] getAssignableUsers(String projectKey);
//
// }
// Path: src/main/java/org/agilos/jira/ws/AgilosSoapServiceImpl.java
import com.atlassian.jira.rpc.auth.TokenManager;
import com.atlassian.jira.rpc.exception.RemoteAuthenticationException;
import com.atlassian.jira.rpc.exception.RemoteException;
import com.atlassian.jira.rpc.exception.RemotePermissionException;
import com.atlassian.jira.rpc.soap.beans.RemoteUser;
import com.opensymphony.user.User;
import org.agilos.jira.service.UserService;
import org.apache.log4j.Logger;
package org.agilos.jira.ws;
public class AgilosSoapServiceImpl implements AgilosSoapService {
private TokenManager tokenManager; // The TokenManager functionality is very much inspired by the com.atlassian.jira.rpc.auth.TokenManager
| private UserService userService;
|
zendesk/zendesk-jira-plugin | src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/testcases/WorkflowNotificationTest.java | // Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/AbstractNotificationTest.java
// public abstract class AbstractNotificationTest extends JIRATest {
// public NotificationFixture fixture;
// protected String issueKey;
//
// private Logger log = Logger.getLogger(NotificationTest.class.getName());
//
// @BeforeMethod (alwaysRun = true)
// @Override
// protected void setUpTest() throws Exception {
// super.setUpTest();
// issueKey = fixture.createIssue(PROJECT_KEY).getKey();
// }
//
// @AfterMethod (alwaysRun = true)
// protected void tearDownTest() throws Exception {
// Request request = fixture.getNextRequestInstant();
// if (request != null) log.warn("Notification remains on message queue after testcase has finish" + request.getEntityAsText());
// }
//
// @Override
// protected JIRAFixture getFixture() {
// if (fixture == null ) fixture = new NotificationFixture();
// return fixture;
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/TestDataFactory.java
// public abstract class TestDataFactory {
// private static final Properties properties = loadProperties("testdata");;
//
// public static String getSoapResponse(String ID) {
// return (String)properties.get("soap_response."+ID);
// }
//
// private static Properties loadProperties(String name) {
// if (name == null)
// throw new IllegalArgumentException("null input: name");
//
// if (name.startsWith("/"))
// name = name.substring(1);
//
// if (name.endsWith(SUFFIX))
// name = name.substring(0, name.length() - SUFFIX.length());
//
// Properties result = null;
//
// InputStream in = null;
//
// try {
// name = name.replace('/', '.');
// // Throws MissingResourceException on lookup failures:
// final ResourceBundle rb = ResourceBundle.getBundle(name, Locale
// .getDefault(), ClassLoader.getSystemClassLoader());
//
// result = new Properties();
// for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
// final String key = (String) keys.nextElement();
// final String value = rb.getString(key);
//
// result.put(key, value);
// }
// } catch (Exception e) {
// result = null;
// } finally {
// if (in != null)
// try {
// in.close();
// } catch (Throwable ignore) {
// }
// }
//
// if (THROW_ON_LOAD_FAILURE && (result == null)) {
// throw new IllegalArgumentException("could not load ["+ name +"]");
// }
//
// return result;
// }
//
// private static final boolean THROW_ON_LOAD_FAILURE = true;
// private static final String SUFFIX = ".properties";
// }
| import static org.testng.AssertJUnit.assertEquals;
import it.org.agilos.zendesk_jira_plugin.integrationtest.AbstractNotificationTest;
import org.agilos.zendesk_jira_plugin.testframework.TestDataFactory;
import org.testng.annotations.Test;
| package it.org.agilos.zendesk_jira_plugin.integrationtest.testcases;
public class WorkflowNotificationTest extends AbstractNotificationTest {
@Test (groups = {"regressionTests"} )
public void testDefaultWorkflow() {
selenium.open("browse/"+issueKey);
selenium.isTextPresent("Open");
selenium.click("assign-to-me"); //Need to assign the issue to current user to gain access to all workflow actions
selenium.waitForPageToLoad("3000");
selenium.click("link=Start Progress");
selenium.waitForPageToLoad("3000");
selenium.isTextPresent("In Progress");
assertEquals("Wrong response received setting issue 'In progress'",
| // Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/AbstractNotificationTest.java
// public abstract class AbstractNotificationTest extends JIRATest {
// public NotificationFixture fixture;
// protected String issueKey;
//
// private Logger log = Logger.getLogger(NotificationTest.class.getName());
//
// @BeforeMethod (alwaysRun = true)
// @Override
// protected void setUpTest() throws Exception {
// super.setUpTest();
// issueKey = fixture.createIssue(PROJECT_KEY).getKey();
// }
//
// @AfterMethod (alwaysRun = true)
// protected void tearDownTest() throws Exception {
// Request request = fixture.getNextRequestInstant();
// if (request != null) log.warn("Notification remains on message queue after testcase has finish" + request.getEntityAsText());
// }
//
// @Override
// protected JIRAFixture getFixture() {
// if (fixture == null ) fixture = new NotificationFixture();
// return fixture;
// }
// }
//
// Path: src/test/java/org/agilos/zendesk_jira_plugin/testframework/TestDataFactory.java
// public abstract class TestDataFactory {
// private static final Properties properties = loadProperties("testdata");;
//
// public static String getSoapResponse(String ID) {
// return (String)properties.get("soap_response."+ID);
// }
//
// private static Properties loadProperties(String name) {
// if (name == null)
// throw new IllegalArgumentException("null input: name");
//
// if (name.startsWith("/"))
// name = name.substring(1);
//
// if (name.endsWith(SUFFIX))
// name = name.substring(0, name.length() - SUFFIX.length());
//
// Properties result = null;
//
// InputStream in = null;
//
// try {
// name = name.replace('/', '.');
// // Throws MissingResourceException on lookup failures:
// final ResourceBundle rb = ResourceBundle.getBundle(name, Locale
// .getDefault(), ClassLoader.getSystemClassLoader());
//
// result = new Properties();
// for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
// final String key = (String) keys.nextElement();
// final String value = rb.getString(key);
//
// result.put(key, value);
// }
// } catch (Exception e) {
// result = null;
// } finally {
// if (in != null)
// try {
// in.close();
// } catch (Throwable ignore) {
// }
// }
//
// if (THROW_ON_LOAD_FAILURE && (result == null)) {
// throw new IllegalArgumentException("could not load ["+ name +"]");
// }
//
// return result;
// }
//
// private static final boolean THROW_ON_LOAD_FAILURE = true;
// private static final String SUFFIX = ".properties";
// }
// Path: src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/testcases/WorkflowNotificationTest.java
import static org.testng.AssertJUnit.assertEquals;
import it.org.agilos.zendesk_jira_plugin.integrationtest.AbstractNotificationTest;
import org.agilos.zendesk_jira_plugin.testframework.TestDataFactory;
import org.testng.annotations.Test;
package it.org.agilos.zendesk_jira_plugin.integrationtest.testcases;
public class WorkflowNotificationTest extends AbstractNotificationTest {
@Test (groups = {"regressionTests"} )
public void testDefaultWorkflow() {
selenium.open("browse/"+issueKey);
selenium.isTextPresent("Open");
selenium.click("assign-to-me"); //Need to assign the issue to current user to gain access to all workflow actions
selenium.waitForPageToLoad("3000");
selenium.click("link=Start Progress");
selenium.waitForPageToLoad("3000");
selenium.isTextPresent("In Progress");
assertEquals("Wrong response received setting issue 'In progress'",
| TestDataFactory.getSoapResponse("testDefaultWorkflow.started"),
|
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Point2i.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.maths;
public class Point2i {
public int x, y;
public Point2i(int x, int y) {
this.x = x;
this.y = y;
}
public static Point2i fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Point2i.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.maths;
public class Point2i {
public int x, y;
public Point2i(int x, int y) {
this.x = x;
this.y = y;
}
public static Point2i fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | throw new ConfigException("Invalid point: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/config/SpriteId.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.config;
public class SpriteId {
public final int group, id;
public SpriteId(int group, int id) {
this.group = group;
this.id = id;
}
public static SpriteId fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/config/SpriteId.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.config;
public class SpriteId {
public final int group, id;
public SpriteId(int group, int id) {
this.group = group;
this.id = id;
}
public static SpriteId fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | throw new ConfigException("Invalid sprite id config: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/Level.java | // Path: src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java
// public class Matrix4f {
//
// private float[] elements = new float[16];
// private FloatBuffer buffer;
//
// private Matrix4f() {
// }
//
// public static Matrix4f identity() {
// Matrix4f m = new Matrix4f();
// m.elements[0] = 1.0f;
// m.elements[5] = 1.0f;
// m.elements[10] = 1.0f;
// m.elements[15] = 1.0f;
// return m;
// }
//
// public static Matrix4f orthographic(float left, float right, float top, float bottom, float near, float far) {
// Matrix4f m = identity();
// m.elements[0] = 2.0f / (right - left);
// m.elements[5] = 2.0f / (top - bottom);
// m.elements[10] = 2.0f / (near - far);
// m.elements[12] = (left + right) / (left - right);
// m.elements[13] = (bottom + top) / (bottom - top);
// m.elements[14] = (far + near) / (far - near);
// return m;
// }
//
// /**
// * 1 0 0 x<br>
// * 0 1 0 y<br>
// * 0 0 1 z<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f translate(Vector3f vector) {
// return identity().translateTo(vector);
// }
//
// public Matrix4f translateTo(Vector3f vector) {
// elements[12] = vector.x;
// elements[13] = vector.y;
// elements[14] = vector.z;
// return this;
// }
//
// public Matrix4f translateTo(float x, float y, float z) {
// elements[12] = x;
// elements[13] = y;
// elements[14] = z;
// return this;
// }
//
// public static Matrix4f resize(Vector3f vector) {
// return identity().resizeTo(vector);
// }
//
// public Matrix4f resizeTo(Vector3f vector) {
// elements[0] = vector.x;
// elements[5] = vector.y;
// elements[10] = vector.z;
// return this;
// }
//
// /**
// * cos -sin 0 0<br>
// * sin cos 0 0<br>
// * 0 0 1 0<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f rotate(float angle) {
// Matrix4f m = identity();
// float a = (float) Math.toRadians(angle);
// float cos = (float) Math.cos(a);
// float sin = (float) Math.sin(a);
// m.elements[0] = cos;
// m.elements[1] = sin;
// m.elements[4] = -sin;
// m.elements[5] = cos;
// return m;
// }
//
// public Matrix4f multiply(Matrix4f m2) {
// Matrix4f m = new Matrix4f();
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// float sum = 0;
// for (int k = 0; k < 4; k++) {
// sum += elements[i + k * 4] * m2.elements[j * 4 + k];
// }
// m.elements[i + j * 4] = sum;
// }
// }
// return m;
// }
//
// public FloatBuffer toFloatBuffer() {
// if (buffer == null) {
// buffer = BufferUtils.toFloatBuffer(elements);
// return buffer;
// }
// buffer.rewind();
// buffer.put(elements);
// buffer.flip();
// return buffer;
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/maths/Vector3f.java
// public final class Vector3f {
//
// public final float x, y, z;
//
// public static final Vector3f ZERO = new Vector3f(0f, 0f, 0f);
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
| import org.scorpion.jmugen.core.maths.Matrix4f;
import org.scorpion.jmugen.core.maths.Vector3f;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.render.*;
import org.scorpion.jmugen.util.ClasspathResource; | package org.scorpion.jmugen.core;
public class Level implements Renderable {
private Mesh background;
private Texture bgTexture;
int xScroll = 0, bgMap = 0;
public Level() {
}
@Override
public void init() { | // Path: src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java
// public class Matrix4f {
//
// private float[] elements = new float[16];
// private FloatBuffer buffer;
//
// private Matrix4f() {
// }
//
// public static Matrix4f identity() {
// Matrix4f m = new Matrix4f();
// m.elements[0] = 1.0f;
// m.elements[5] = 1.0f;
// m.elements[10] = 1.0f;
// m.elements[15] = 1.0f;
// return m;
// }
//
// public static Matrix4f orthographic(float left, float right, float top, float bottom, float near, float far) {
// Matrix4f m = identity();
// m.elements[0] = 2.0f / (right - left);
// m.elements[5] = 2.0f / (top - bottom);
// m.elements[10] = 2.0f / (near - far);
// m.elements[12] = (left + right) / (left - right);
// m.elements[13] = (bottom + top) / (bottom - top);
// m.elements[14] = (far + near) / (far - near);
// return m;
// }
//
// /**
// * 1 0 0 x<br>
// * 0 1 0 y<br>
// * 0 0 1 z<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f translate(Vector3f vector) {
// return identity().translateTo(vector);
// }
//
// public Matrix4f translateTo(Vector3f vector) {
// elements[12] = vector.x;
// elements[13] = vector.y;
// elements[14] = vector.z;
// return this;
// }
//
// public Matrix4f translateTo(float x, float y, float z) {
// elements[12] = x;
// elements[13] = y;
// elements[14] = z;
// return this;
// }
//
// public static Matrix4f resize(Vector3f vector) {
// return identity().resizeTo(vector);
// }
//
// public Matrix4f resizeTo(Vector3f vector) {
// elements[0] = vector.x;
// elements[5] = vector.y;
// elements[10] = vector.z;
// return this;
// }
//
// /**
// * cos -sin 0 0<br>
// * sin cos 0 0<br>
// * 0 0 1 0<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f rotate(float angle) {
// Matrix4f m = identity();
// float a = (float) Math.toRadians(angle);
// float cos = (float) Math.cos(a);
// float sin = (float) Math.sin(a);
// m.elements[0] = cos;
// m.elements[1] = sin;
// m.elements[4] = -sin;
// m.elements[5] = cos;
// return m;
// }
//
// public Matrix4f multiply(Matrix4f m2) {
// Matrix4f m = new Matrix4f();
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// float sum = 0;
// for (int k = 0; k < 4; k++) {
// sum += elements[i + k * 4] * m2.elements[j * 4 + k];
// }
// m.elements[i + j * 4] = sum;
// }
// }
// return m;
// }
//
// public FloatBuffer toFloatBuffer() {
// if (buffer == null) {
// buffer = BufferUtils.toFloatBuffer(elements);
// return buffer;
// }
// buffer.rewind();
// buffer.put(elements);
// buffer.flip();
// return buffer;
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/maths/Vector3f.java
// public final class Vector3f {
//
// public final float x, y, z;
//
// public static final Vector3f ZERO = new Vector3f(0f, 0f, 0f);
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
// Path: src/main/java/org/scorpion/jmugen/core/Level.java
import org.scorpion.jmugen.core.maths.Matrix4f;
import org.scorpion.jmugen.core.maths.Vector3f;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.render.*;
import org.scorpion.jmugen.util.ClasspathResource;
package org.scorpion.jmugen.core;
public class Level implements Renderable {
private Mesh background;
private Texture bgTexture;
int xScroll = 0, bgMap = 0;
public Level() {
}
@Override
public void init() { | background = new RectangularMesh(new Vector3f(-10.0f, -10.0f * 9.0f / 16.0f, 0.0f), new Vector3f(10.0f, 10.0f * 9.0f / 16.0f, 0.0f)); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/Level.java | // Path: src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java
// public class Matrix4f {
//
// private float[] elements = new float[16];
// private FloatBuffer buffer;
//
// private Matrix4f() {
// }
//
// public static Matrix4f identity() {
// Matrix4f m = new Matrix4f();
// m.elements[0] = 1.0f;
// m.elements[5] = 1.0f;
// m.elements[10] = 1.0f;
// m.elements[15] = 1.0f;
// return m;
// }
//
// public static Matrix4f orthographic(float left, float right, float top, float bottom, float near, float far) {
// Matrix4f m = identity();
// m.elements[0] = 2.0f / (right - left);
// m.elements[5] = 2.0f / (top - bottom);
// m.elements[10] = 2.0f / (near - far);
// m.elements[12] = (left + right) / (left - right);
// m.elements[13] = (bottom + top) / (bottom - top);
// m.elements[14] = (far + near) / (far - near);
// return m;
// }
//
// /**
// * 1 0 0 x<br>
// * 0 1 0 y<br>
// * 0 0 1 z<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f translate(Vector3f vector) {
// return identity().translateTo(vector);
// }
//
// public Matrix4f translateTo(Vector3f vector) {
// elements[12] = vector.x;
// elements[13] = vector.y;
// elements[14] = vector.z;
// return this;
// }
//
// public Matrix4f translateTo(float x, float y, float z) {
// elements[12] = x;
// elements[13] = y;
// elements[14] = z;
// return this;
// }
//
// public static Matrix4f resize(Vector3f vector) {
// return identity().resizeTo(vector);
// }
//
// public Matrix4f resizeTo(Vector3f vector) {
// elements[0] = vector.x;
// elements[5] = vector.y;
// elements[10] = vector.z;
// return this;
// }
//
// /**
// * cos -sin 0 0<br>
// * sin cos 0 0<br>
// * 0 0 1 0<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f rotate(float angle) {
// Matrix4f m = identity();
// float a = (float) Math.toRadians(angle);
// float cos = (float) Math.cos(a);
// float sin = (float) Math.sin(a);
// m.elements[0] = cos;
// m.elements[1] = sin;
// m.elements[4] = -sin;
// m.elements[5] = cos;
// return m;
// }
//
// public Matrix4f multiply(Matrix4f m2) {
// Matrix4f m = new Matrix4f();
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// float sum = 0;
// for (int k = 0; k < 4; k++) {
// sum += elements[i + k * 4] * m2.elements[j * 4 + k];
// }
// m.elements[i + j * 4] = sum;
// }
// }
// return m;
// }
//
// public FloatBuffer toFloatBuffer() {
// if (buffer == null) {
// buffer = BufferUtils.toFloatBuffer(elements);
// return buffer;
// }
// buffer.rewind();
// buffer.put(elements);
// buffer.flip();
// return buffer;
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/maths/Vector3f.java
// public final class Vector3f {
//
// public final float x, y, z;
//
// public static final Vector3f ZERO = new Vector3f(0f, 0f, 0f);
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
| import org.scorpion.jmugen.core.maths.Matrix4f;
import org.scorpion.jmugen.core.maths.Vector3f;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.render.*;
import org.scorpion.jmugen.util.ClasspathResource; | package org.scorpion.jmugen.core;
public class Level implements Renderable {
private Mesh background;
private Texture bgTexture;
int xScroll = 0, bgMap = 0;
public Level() {
}
@Override
public void init() {
background = new RectangularMesh(new Vector3f(-10.0f, -10.0f * 9.0f / 16.0f, 0.0f), new Vector3f(10.0f, 10.0f * 9.0f / 16.0f, 0.0f)); | // Path: src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java
// public class Matrix4f {
//
// private float[] elements = new float[16];
// private FloatBuffer buffer;
//
// private Matrix4f() {
// }
//
// public static Matrix4f identity() {
// Matrix4f m = new Matrix4f();
// m.elements[0] = 1.0f;
// m.elements[5] = 1.0f;
// m.elements[10] = 1.0f;
// m.elements[15] = 1.0f;
// return m;
// }
//
// public static Matrix4f orthographic(float left, float right, float top, float bottom, float near, float far) {
// Matrix4f m = identity();
// m.elements[0] = 2.0f / (right - left);
// m.elements[5] = 2.0f / (top - bottom);
// m.elements[10] = 2.0f / (near - far);
// m.elements[12] = (left + right) / (left - right);
// m.elements[13] = (bottom + top) / (bottom - top);
// m.elements[14] = (far + near) / (far - near);
// return m;
// }
//
// /**
// * 1 0 0 x<br>
// * 0 1 0 y<br>
// * 0 0 1 z<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f translate(Vector3f vector) {
// return identity().translateTo(vector);
// }
//
// public Matrix4f translateTo(Vector3f vector) {
// elements[12] = vector.x;
// elements[13] = vector.y;
// elements[14] = vector.z;
// return this;
// }
//
// public Matrix4f translateTo(float x, float y, float z) {
// elements[12] = x;
// elements[13] = y;
// elements[14] = z;
// return this;
// }
//
// public static Matrix4f resize(Vector3f vector) {
// return identity().resizeTo(vector);
// }
//
// public Matrix4f resizeTo(Vector3f vector) {
// elements[0] = vector.x;
// elements[5] = vector.y;
// elements[10] = vector.z;
// return this;
// }
//
// /**
// * cos -sin 0 0<br>
// * sin cos 0 0<br>
// * 0 0 1 0<br>
// * 0 0 0 1<br>
// */
// public static Matrix4f rotate(float angle) {
// Matrix4f m = identity();
// float a = (float) Math.toRadians(angle);
// float cos = (float) Math.cos(a);
// float sin = (float) Math.sin(a);
// m.elements[0] = cos;
// m.elements[1] = sin;
// m.elements[4] = -sin;
// m.elements[5] = cos;
// return m;
// }
//
// public Matrix4f multiply(Matrix4f m2) {
// Matrix4f m = new Matrix4f();
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// float sum = 0;
// for (int k = 0; k < 4; k++) {
// sum += elements[i + k * 4] * m2.elements[j * 4 + k];
// }
// m.elements[i + j * 4] = sum;
// }
// }
// return m;
// }
//
// public FloatBuffer toFloatBuffer() {
// if (buffer == null) {
// buffer = BufferUtils.toFloatBuffer(elements);
// return buffer;
// }
// buffer.rewind();
// buffer.put(elements);
// buffer.flip();
// return buffer;
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/maths/Vector3f.java
// public final class Vector3f {
//
// public final float x, y, z;
//
// public static final Vector3f ZERO = new Vector3f(0f, 0f, 0f);
//
// public Vector3f(float x, float y, float z) {
// this.x = x;
// this.y = y;
// this.z = z;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
// Path: src/main/java/org/scorpion/jmugen/core/Level.java
import org.scorpion.jmugen.core.maths.Matrix4f;
import org.scorpion.jmugen.core.maths.Vector3f;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.render.*;
import org.scorpion.jmugen.util.ClasspathResource;
package org.scorpion.jmugen.core;
public class Level implements Renderable {
private Mesh background;
private Texture bgTexture;
int xScroll = 0, bgMap = 0;
public Level() {
}
@Override
public void init() {
background = new RectangularMesh(new Vector3f(-10.0f, -10.0f * 9.0f / 16.0f, 0.0f), new Vector3f(10.0f, 10.0f * 9.0f / 16.0f, 0.0f)); | bgTexture = new Texture(new ClasspathResource("images/Desert.jpg")); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Range.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.maths;
public class Range {
public final float start, end;
public Range(float start, float end) {
this.start = start;
this.end = end;
}
public static Range fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Range.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.maths;
public class Range {
public final float start, end;
public Range(float start, float end) {
this.start = start;
this.end = end;
}
public static Range fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | throw new ConfigException("Invalid range: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/render/util/ShaderUtils.java | // Path: src/main/java/org/scorpion/jmugen/exception/InitializationError.java
// public class InitializationError extends Error implements Fatal {
//
// public InitializationError(String message) {
// super(message);
// }
//
// public InitializationError(String message, String reason) {
// super(message + ":\n" + reason);
// }
//
// public InitializationError(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
| import org.apache.commons.io.IOUtils;
import org.scorpion.jmugen.exception.InitializationError;
import org.scorpion.jmugen.util.Resource;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import java.io.IOException; | package org.scorpion.jmugen.render.util;
public class ShaderUtils {
public static int loadShaders(Resource vertex, Resource fragment) {
int p = glCreateProgram();
int vertexShaderId = loadAndAttachShader(p, GL_VERTEX_SHADER, vertex);
int fragmentShaderId = loadAndAttachShader(p, GL_FRAGMENT_SHADER, fragment);
glLinkProgram(p);
if (glGetProgrami(p, GL_LINK_STATUS) == GL_FALSE) {
String log = glGetProgramInfoLog(p, glGetProgrami(p, GL_INFO_LOG_LENGTH)); | // Path: src/main/java/org/scorpion/jmugen/exception/InitializationError.java
// public class InitializationError extends Error implements Fatal {
//
// public InitializationError(String message) {
// super(message);
// }
//
// public InitializationError(String message, String reason) {
// super(message + ":\n" + reason);
// }
//
// public InitializationError(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
// Path: src/main/java/org/scorpion/jmugen/render/util/ShaderUtils.java
import org.apache.commons.io.IOUtils;
import org.scorpion.jmugen.exception.InitializationError;
import org.scorpion.jmugen.util.Resource;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import java.io.IOException;
package org.scorpion.jmugen.render.util;
public class ShaderUtils {
public static int loadShaders(Resource vertex, Resource fragment) {
int p = glCreateProgram();
int vertexShaderId = loadAndAttachShader(p, GL_VERTEX_SHADER, vertex);
int fragmentShaderId = loadAndAttachShader(p, GL_FRAGMENT_SHADER, fragment);
glLinkProgram(p);
if (glGetProgrami(p, GL_LINK_STATUS) == GL_FALSE) {
String log = glGetProgramInfoLog(p, glGetProgrami(p, GL_INFO_LOG_LENGTH)); | throw new InitializationError("Failed to link program " + vertex + " " + fragment, log); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Point2f.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.maths;
public class Point2f {
public float x, y;
public Point2f(float x, float y) {
this.x = x;
this.y = y;
}
public static Point2f fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Point2f.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.maths;
public class Point2f {
public float x, y;
public Point2f(float x, float y) {
this.x = x;
this.y = y;
}
public static Point2f fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 2) { | throw new ConfigException("Invalid point: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/render/Shaders.java | // Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
| import org.scorpion.jmugen.util.ClasspathResource; | package org.scorpion.jmugen.render;
public class Shaders {
private static Shader backgroundShader;
public static void loadBackgroundShader() { | // Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
// public class ClasspathResource implements Resource {
//
// private String path;
//
// public ClasspathResource(String path) {
// this.path = path;
// }
//
// @Override
// public InputStream load() {
// InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
// if (in == null) {
// throw new GenericIOException(path + " not found");
// }
// return in;
// }
//
// @Override
// public String getName() {
// return path;
// }
//
// @Override
// public String toString() {
// return getName();
// }
// }
// Path: src/main/java/org/scorpion/jmugen/render/Shaders.java
import org.scorpion.jmugen.util.ClasspathResource;
package org.scorpion.jmugen.render;
public class Shaders {
private static Shader backgroundShader;
public static void loadBackgroundShader() { | backgroundShader = new Shader("Background", new ClasspathResource("shaders/bg.vert"), new ClasspathResource("shaders/bg.frag")); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/config/Config.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
import java.util.*;
import java.util.function.Function; | }
for (Map.Entry<String, Object> entry : that.container.entrySet()) {
String key = entry.getKey();
Object thisValue = container.get(key);
Object thatValue = entry.getValue();
if (thisValue == null || !(thisValue instanceof Config) && !(thatValue instanceof Config)) {
container.put(key, thatValue);
continue;
}
if (!(thisValue instanceof Config)) {
Config sub = convertToGroup(key);
sub.merge((Config) thatValue);
continue;
}
if (!(thatValue instanceof Config)) {
((Config) thisValue).container.put(null, thatValue);
continue;
}
((Config) thisValue).merge((Config) thatValue);
}
return this;
}
public <T> Config applyConverters(Map<String, ? extends Function<? super T, ?>> converters) {
converters.forEach((key, converter) -> {
String[] keys = StringUtils.split(key, '.');
T config = get(keys);
if (config != null) {
add(keys, converter.apply(config));
} else { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/config/Config.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
import java.util.*;
import java.util.function.Function;
}
for (Map.Entry<String, Object> entry : that.container.entrySet()) {
String key = entry.getKey();
Object thisValue = container.get(key);
Object thatValue = entry.getValue();
if (thisValue == null || !(thisValue instanceof Config) && !(thatValue instanceof Config)) {
container.put(key, thatValue);
continue;
}
if (!(thisValue instanceof Config)) {
Config sub = convertToGroup(key);
sub.merge((Config) thatValue);
continue;
}
if (!(thatValue instanceof Config)) {
((Config) thisValue).container.put(null, thatValue);
continue;
}
((Config) thisValue).merge((Config) thatValue);
}
return this;
}
public <T> Config applyConverters(Map<String, ? extends Function<? super T, ?>> converters) {
converters.forEach((key, converter) -> {
String[] keys = StringUtils.split(key, '.');
T config = get(keys);
if (config != null) {
add(keys, converter.apply(config));
} else { | throw new ConfigException(key + " is missing in config"); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/util/FileResource.java | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*; | package org.scorpion.jmugen.util;
public class FileResource implements Resource {
private static final String CURRENT_DIR = new File("").getAbsolutePath();
private File file;
public FileResource(String file) {
this(new File(file));
}
public FileResource(File file) {
if (file.isAbsolute()) {
this.file = file;
} else {
this.file = new File(CURRENT_DIR + File.separator + file.getPath());
}
this.file = file;
}
@Override
public InputStream load() {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) { | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/org/scorpion/jmugen/util/FileResource.java
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*;
package org.scorpion.jmugen.util;
public class FileResource implements Resource {
private static final String CURRENT_DIR = new File("").getAbsolutePath();
private File file;
public FileResource(String file) {
this(new File(file));
}
public FileResource(File file) {
if (file.isAbsolute()) {
this.file = file;
} else {
this.file = new File(CURRENT_DIR + File.separator + file.getPath());
}
this.file = file;
}
@Override
public InputStream load() {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) { | throw new GenericIOException(e); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/element/GameObject.java | // Path: src/main/java/org/scorpion/jmugen/core/config/Def.java
// public interface Def<T> extends Loadable<T> {
//
// Function<String, Boolean> BOOLEAN_CONVERTER = input -> Integer.parseInt(input) != 0;
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/config/SystemConfig.java
// public class SystemConfig {
//
// private int windowWidth;
// private int windowHeight;
// private int gameWidth;
// private int gameHeight;
// private String resourceHome;
//
// public SystemConfig(Map<String, String> configs) {
// windowWidth = Integer.parseInt(configs.get(ConfigKeys.HORIZONTAL_RES));
// windowHeight = Integer.parseInt(configs.get(ConfigKeys.VERTICAL_RES));
// gameWidth = Integer.parseInt(configs.get(ConfigKeys.GAME_WIDTH));
// gameHeight = Integer.parseInt(configs.get(ConfigKeys.GAME_HEIGHT));
// resourceHome = configs.get(ConfigKeys.RESOURCE_HOME);
// }
//
// public int getWindowWidth() {
// return windowWidth;
// }
//
// public int getWindowHeight() {
// return windowHeight;
// }
//
// public int getGameWidth() {
// return gameWidth;
// }
//
// public int getGameHeight() {
// return gameHeight;
// }
//
// public String getResourceHome() {
// return resourceHome;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/io/input/keyboard/KeyboardInputHandler.java
// public class KeyboardInputHandler extends GLFWKeyCallback {
//
// protected boolean[] keys = new boolean[4096];
// private Map<Integer, List<KeyStrokeHandler>> keyStrokeHandlers = new HashMap<>();
//
// @Override
// public void invoke(long window, int key, int scancode, int action, int mods) {
// keys[key] = action == GLFW.GLFW_PRESS || action == GLFW.GLFW_REPEAT;
// if (action == GLFW.GLFW_PRESS) {
// keyStrokeHandlers.getOrDefault(key, Collections.emptyList()).forEach(h -> h.onKey(mods));
// }
// }
//
// public void registerStrokeHandler(int code, KeyStrokeHandler handler) {
// keyStrokeHandlers
// .computeIfAbsent(code, k -> new ArrayList<>())
// .add(handler);
// }
//
// public boolean isKeyPressed(int key) {
// return keys[key];
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Loadable.java
// public interface Loadable<T> {
//
// T load();
//
// }
| import org.scorpion.jmugen.core.config.Def;
import org.scorpion.jmugen.core.config.SystemConfig;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.io.input.keyboard.KeyboardInputHandler;
import org.scorpion.jmugen.util.Loadable; | package org.scorpion.jmugen.core.element;
public abstract class GameObject<D extends Def> implements Renderable, Loadable<Void> {
protected D config; | // Path: src/main/java/org/scorpion/jmugen/core/config/Def.java
// public interface Def<T> extends Loadable<T> {
//
// Function<String, Boolean> BOOLEAN_CONVERTER = input -> Integer.parseInt(input) != 0;
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/config/SystemConfig.java
// public class SystemConfig {
//
// private int windowWidth;
// private int windowHeight;
// private int gameWidth;
// private int gameHeight;
// private String resourceHome;
//
// public SystemConfig(Map<String, String> configs) {
// windowWidth = Integer.parseInt(configs.get(ConfigKeys.HORIZONTAL_RES));
// windowHeight = Integer.parseInt(configs.get(ConfigKeys.VERTICAL_RES));
// gameWidth = Integer.parseInt(configs.get(ConfigKeys.GAME_WIDTH));
// gameHeight = Integer.parseInt(configs.get(ConfigKeys.GAME_HEIGHT));
// resourceHome = configs.get(ConfigKeys.RESOURCE_HOME);
// }
//
// public int getWindowWidth() {
// return windowWidth;
// }
//
// public int getWindowHeight() {
// return windowHeight;
// }
//
// public int getGameWidth() {
// return gameWidth;
// }
//
// public int getGameHeight() {
// return gameHeight;
// }
//
// public String getResourceHome() {
// return resourceHome;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/io/input/keyboard/KeyboardInputHandler.java
// public class KeyboardInputHandler extends GLFWKeyCallback {
//
// protected boolean[] keys = new boolean[4096];
// private Map<Integer, List<KeyStrokeHandler>> keyStrokeHandlers = new HashMap<>();
//
// @Override
// public void invoke(long window, int key, int scancode, int action, int mods) {
// keys[key] = action == GLFW.GLFW_PRESS || action == GLFW.GLFW_REPEAT;
// if (action == GLFW.GLFW_PRESS) {
// keyStrokeHandlers.getOrDefault(key, Collections.emptyList()).forEach(h -> h.onKey(mods));
// }
// }
//
// public void registerStrokeHandler(int code, KeyStrokeHandler handler) {
// keyStrokeHandlers
// .computeIfAbsent(code, k -> new ArrayList<>())
// .add(handler);
// }
//
// public boolean isKeyPressed(int key) {
// return keys[key];
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Loadable.java
// public interface Loadable<T> {
//
// T load();
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/element/GameObject.java
import org.scorpion.jmugen.core.config.Def;
import org.scorpion.jmugen.core.config.SystemConfig;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.io.input.keyboard.KeyboardInputHandler;
import org.scorpion.jmugen.util.Loadable;
package org.scorpion.jmugen.core.element;
public abstract class GameObject<D extends Def> implements Renderable, Loadable<Void> {
protected D config; | protected SystemConfig systemConfig; |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/element/GameObject.java | // Path: src/main/java/org/scorpion/jmugen/core/config/Def.java
// public interface Def<T> extends Loadable<T> {
//
// Function<String, Boolean> BOOLEAN_CONVERTER = input -> Integer.parseInt(input) != 0;
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/config/SystemConfig.java
// public class SystemConfig {
//
// private int windowWidth;
// private int windowHeight;
// private int gameWidth;
// private int gameHeight;
// private String resourceHome;
//
// public SystemConfig(Map<String, String> configs) {
// windowWidth = Integer.parseInt(configs.get(ConfigKeys.HORIZONTAL_RES));
// windowHeight = Integer.parseInt(configs.get(ConfigKeys.VERTICAL_RES));
// gameWidth = Integer.parseInt(configs.get(ConfigKeys.GAME_WIDTH));
// gameHeight = Integer.parseInt(configs.get(ConfigKeys.GAME_HEIGHT));
// resourceHome = configs.get(ConfigKeys.RESOURCE_HOME);
// }
//
// public int getWindowWidth() {
// return windowWidth;
// }
//
// public int getWindowHeight() {
// return windowHeight;
// }
//
// public int getGameWidth() {
// return gameWidth;
// }
//
// public int getGameHeight() {
// return gameHeight;
// }
//
// public String getResourceHome() {
// return resourceHome;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/io/input/keyboard/KeyboardInputHandler.java
// public class KeyboardInputHandler extends GLFWKeyCallback {
//
// protected boolean[] keys = new boolean[4096];
// private Map<Integer, List<KeyStrokeHandler>> keyStrokeHandlers = new HashMap<>();
//
// @Override
// public void invoke(long window, int key, int scancode, int action, int mods) {
// keys[key] = action == GLFW.GLFW_PRESS || action == GLFW.GLFW_REPEAT;
// if (action == GLFW.GLFW_PRESS) {
// keyStrokeHandlers.getOrDefault(key, Collections.emptyList()).forEach(h -> h.onKey(mods));
// }
// }
//
// public void registerStrokeHandler(int code, KeyStrokeHandler handler) {
// keyStrokeHandlers
// .computeIfAbsent(code, k -> new ArrayList<>())
// .add(handler);
// }
//
// public boolean isKeyPressed(int key) {
// return keys[key];
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Loadable.java
// public interface Loadable<T> {
//
// T load();
//
// }
| import org.scorpion.jmugen.core.config.Def;
import org.scorpion.jmugen.core.config.SystemConfig;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.io.input.keyboard.KeyboardInputHandler;
import org.scorpion.jmugen.util.Loadable; | package org.scorpion.jmugen.core.element;
public abstract class GameObject<D extends Def> implements Renderable, Loadable<Void> {
protected D config;
protected SystemConfig systemConfig; | // Path: src/main/java/org/scorpion/jmugen/core/config/Def.java
// public interface Def<T> extends Loadable<T> {
//
// Function<String, Boolean> BOOLEAN_CONVERTER = input -> Integer.parseInt(input) != 0;
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/config/SystemConfig.java
// public class SystemConfig {
//
// private int windowWidth;
// private int windowHeight;
// private int gameWidth;
// private int gameHeight;
// private String resourceHome;
//
// public SystemConfig(Map<String, String> configs) {
// windowWidth = Integer.parseInt(configs.get(ConfigKeys.HORIZONTAL_RES));
// windowHeight = Integer.parseInt(configs.get(ConfigKeys.VERTICAL_RES));
// gameWidth = Integer.parseInt(configs.get(ConfigKeys.GAME_WIDTH));
// gameHeight = Integer.parseInt(configs.get(ConfigKeys.GAME_HEIGHT));
// resourceHome = configs.get(ConfigKeys.RESOURCE_HOME);
// }
//
// public int getWindowWidth() {
// return windowWidth;
// }
//
// public int getWindowHeight() {
// return windowHeight;
// }
//
// public int getGameWidth() {
// return gameWidth;
// }
//
// public int getGameHeight() {
// return gameHeight;
// }
//
// public String getResourceHome() {
// return resourceHome;
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/core/render/Renderable.java
// public interface Renderable {
//
// /**
// * called once
// */
// public void init();
//
// /**
// * bind resources, called for each frame
// */
// public void render();
//
// /**
// * update coords, etc.
// */
// public void update();
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/io/input/keyboard/KeyboardInputHandler.java
// public class KeyboardInputHandler extends GLFWKeyCallback {
//
// protected boolean[] keys = new boolean[4096];
// private Map<Integer, List<KeyStrokeHandler>> keyStrokeHandlers = new HashMap<>();
//
// @Override
// public void invoke(long window, int key, int scancode, int action, int mods) {
// keys[key] = action == GLFW.GLFW_PRESS || action == GLFW.GLFW_REPEAT;
// if (action == GLFW.GLFW_PRESS) {
// keyStrokeHandlers.getOrDefault(key, Collections.emptyList()).forEach(h -> h.onKey(mods));
// }
// }
//
// public void registerStrokeHandler(int code, KeyStrokeHandler handler) {
// keyStrokeHandlers
// .computeIfAbsent(code, k -> new ArrayList<>())
// .add(handler);
// }
//
// public boolean isKeyPressed(int key) {
// return keys[key];
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Loadable.java
// public interface Loadable<T> {
//
// T load();
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/element/GameObject.java
import org.scorpion.jmugen.core.config.Def;
import org.scorpion.jmugen.core.config.SystemConfig;
import org.scorpion.jmugen.core.render.Renderable;
import org.scorpion.jmugen.io.input.keyboard.KeyboardInputHandler;
import org.scorpion.jmugen.util.Loadable;
package org.scorpion.jmugen.core.element;
public abstract class GameObject<D extends Def> implements Renderable, Loadable<Void> {
protected D config;
protected SystemConfig systemConfig; | protected KeyboardInputHandler keyboardInputHandler; |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/util/ClasspathResource.java | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import org.scorpion.jmugen.exception.GenericIOException;
import java.io.InputStream; | package org.scorpion.jmugen.util;
public class ClasspathResource implements Resource {
private String path;
public ClasspathResource(String path) {
this.path = path;
}
@Override
public InputStream load() {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (in == null) { | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/org/scorpion/jmugen/util/ClasspathResource.java
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.InputStream;
package org.scorpion.jmugen.util;
public class ClasspathResource implements Resource {
private String path;
public ClasspathResource(String path) {
this.path = path;
}
@Override
public InputStream load() {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (in == null) { | throw new GenericIOException(path + " not found"); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/config/StageDef.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.core.maths.*;
import org.scorpion.jmugen.exception.ConfigException;
import java.util.*;
import java.util.function.Function; | }
public int getTileX() {
return ((Point2i) config.get(TILE)).x;
}
public int getTileY() {
return ((Point2i) config.get(TILE)).y;
}
public int getTileSpacingX() {
return ((Point2i) config.get(TILE_SPACING)).x;
}
public int getTileSpacingY() {
return ((Point2i) config.get(TILE_SPACING)).y;
}
public Trans getTrans() {
return config.get(TRANS);
}
public float getAlphaModifier() {
Point2i alphaConfig = config.get(ALPHA);
return ((float) alphaConfig.x) / (alphaConfig.x + alphaConfig.y);
}
@Override
public BG load() {
if (config.get(SPRITE_NO) == null) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/config/StageDef.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.core.maths.*;
import org.scorpion.jmugen.exception.ConfigException;
import java.util.*;
import java.util.function.Function;
}
public int getTileX() {
return ((Point2i) config.get(TILE)).x;
}
public int getTileY() {
return ((Point2i) config.get(TILE)).y;
}
public int getTileSpacingX() {
return ((Point2i) config.get(TILE_SPACING)).x;
}
public int getTileSpacingY() {
return ((Point2i) config.get(TILE_SPACING)).y;
}
public Trans getTrans() {
return config.get(TRANS);
}
public float getAlphaModifier() {
Point2i alphaConfig = config.get(ALPHA);
return ((float) alphaConfig.x) / (alphaConfig.x + alphaConfig.y);
}
@Override
public BG load() {
if (config.get(SPRITE_NO) == null) { | throw new ConfigException("Sprite no. is missing in BG " + name); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/config/DefParser.java | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.GenericIOException;
import org.scorpion.jmugen.util.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package org.scorpion.jmugen.core.config;
public class DefParser {
private static final String COMMENT_PATTERN = "\\s*(;.*)?";
private static final Pattern COMMENT_OR_EMPTY = Pattern.compile(COMMENT_PATTERN);
private static final Pattern GROUP = Pattern.compile("\\[([^\\[\\]]*)\\]");
private static final Pattern KEY_VALUE_PAIR = Pattern.compile("([^;]*)=([^;]*)" + COMMENT_PATTERN);
private static final Logger LOG = LoggerFactory.getLogger(DefParser.class);
| // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/config/DefParser.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.GenericIOException;
import org.scorpion.jmugen.util.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package org.scorpion.jmugen.core.config;
public class DefParser {
private static final String COMMENT_PATTERN = "\\s*(;.*)?";
private static final Pattern COMMENT_OR_EMPTY = Pattern.compile(COMMENT_PATTERN);
private static final Pattern GROUP = Pattern.compile("\\[([^\\[\\]]*)\\]");
private static final Pattern KEY_VALUE_PAIR = Pattern.compile("([^;]*)=([^;]*)" + COMMENT_PATTERN);
private static final Logger LOG = LoggerFactory.getLogger(DefParser.class);
| public static GroupedConfig parse(Resource resource) { |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/config/DefParser.java | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.GenericIOException;
import org.scorpion.jmugen.util.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | configBuilder.add(group, groupConfigBuilder.get());
groupConfigBuilder = Config.Builder.newConfig();
}
group = groupMatcher.group(1).trim().toLowerCase();
continue;
}
}
{
Matcher keyValueMatcher = KEY_VALUE_PAIR.matcher(line);
if (keyValueMatcher.find()) {
String key = keyValueMatcher.group(1).trim().toLowerCase();
String value = keyValueMatcher.group(2).trim();
if (value.startsWith("\"") && value.endsWith("\"") && value.length() >= 2) {
value = value.substring(1, value.length() - 1);
}
if (groupConfigBuilder == null) {
groupConfigBuilder = Config.Builder.newConfig();
}
groupConfigBuilder.add(key, value);
continue;
}
}
LOG.warn(String.format("Unrecognizable config (%s): %s", resource.getName(), line));
}
// add the last group
if (groupConfigBuilder != null) {
configBuilder.add(group, groupConfigBuilder.get());
}
return configBuilder.get();
} catch (IOException e) { | // Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/scorpion/jmugen/util/Resource.java
// public interface Resource {
//
// InputStream load();
//
// String getName();
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/config/DefParser.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.GenericIOException;
import org.scorpion.jmugen.util.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
configBuilder.add(group, groupConfigBuilder.get());
groupConfigBuilder = Config.Builder.newConfig();
}
group = groupMatcher.group(1).trim().toLowerCase();
continue;
}
}
{
Matcher keyValueMatcher = KEY_VALUE_PAIR.matcher(line);
if (keyValueMatcher.find()) {
String key = keyValueMatcher.group(1).trim().toLowerCase();
String value = keyValueMatcher.group(2).trim();
if (value.startsWith("\"") && value.endsWith("\"") && value.length() >= 2) {
value = value.substring(1, value.length() - 1);
}
if (groupConfigBuilder == null) {
groupConfigBuilder = Config.Builder.newConfig();
}
groupConfigBuilder.add(key, value);
continue;
}
}
LOG.warn(String.format("Unrecognizable config (%s): %s", resource.getName(), line));
}
// add the last group
if (groupConfigBuilder != null) {
configBuilder.add(group, groupConfigBuilder.get());
}
return configBuilder.get();
} catch (IOException e) { | throw new GenericIOException(e); |
xunnanxu/JMugen | src/test/java/org/scorpion/jmugen/core/config/DefParserTest.java | // Path: src/test/java/org/scorpion/jmugen/util/StringResource.java
// public class StringResource implements Resource {
//
// InputStream in;
//
// public StringResource(String str) {
// in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
// }
//
// @Override
// public InputStream load() {
// return in;
// }
//
// @Override
// public String getName() {
// return "string";
// }
// }
| import org.junit.Test;
import org.scorpion.jmugen.util.StringResource;
import static org.junit.Assert.*; | package org.scorpion.jmugen.core.config;
public class DefParserTest {
@Test
public void testParse() throws Exception {
String str = ";comment\n[GROUP]; group comment\n;blfd\n\nstage.1=abc;stage config\n[abc]\na=b\naaa"; | // Path: src/test/java/org/scorpion/jmugen/util/StringResource.java
// public class StringResource implements Resource {
//
// InputStream in;
//
// public StringResource(String str) {
// in = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
// }
//
// @Override
// public InputStream load() {
// return in;
// }
//
// @Override
// public String getName() {
// return "string";
// }
// }
// Path: src/test/java/org/scorpion/jmugen/core/config/DefParserTest.java
import org.junit.Test;
import org.scorpion.jmugen.util.StringResource;
import static org.junit.Assert.*;
package org.scorpion.jmugen.core.config;
public class DefParserTest {
@Test
public void testParse() throws Exception {
String str = ";comment\n[GROUP]; group comment\n;blfd\n\nstage.1=abc;stage config\n[abc]\na=b\naaa"; | GroupedConfig config = DefParser.parse(new StringResource(str)); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Rectangle4f.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.maths;
public class Rectangle4f {
public final Point2f leftBottom, rightTop;
public Rectangle4f(Point2f leftBottom, Point2f rightTop) {
this.leftBottom = leftBottom;
this.rightTop = rightTop;
}
public static Rectangle4f fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 4) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Rectangle4f.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.maths;
public class Rectangle4f {
public final Point2f leftBottom, rightTop;
public Rectangle4f(Point2f leftBottom, Point2f rightTop) {
this.leftBottom = leftBottom;
this.rightTop = rightTop;
}
public static Rectangle4f fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 4) { | throw new ConfigException("Invalid rectangle: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/format/PCXSprite.java | // Path: src/main/java/org/scorpion/jmugen/core/maths/Point2i.java
// public class Point2i {
// public int x, y;
//
// public Point2i(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// public static Point2i fromString(String input) {
// String[] config = StringUtils.split(input, ',');
// if (config == null || config.length < 2) {
// throw new ConfigException("Invalid point: " + input);
// }
// int x = Integer.parseInt(config[0].trim());
// int y = Integer.parseInt(config[1].trim());
// return new Point2i(x, y);
// }
//
// @Override
// public String toString() {
// return "(" + x + ", " + y + ")";
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.common.io.LittleEndianDataInputStream;
import org.scorpion.jmugen.core.maths.Point2i;
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*; | package org.scorpion.jmugen.core.format;
public class PCXSprite implements Sprite {
protected byte[] data;
protected PCXPalette palette;
protected PCXHeader pcxHeader; | // Path: src/main/java/org/scorpion/jmugen/core/maths/Point2i.java
// public class Point2i {
// public int x, y;
//
// public Point2i(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// public static Point2i fromString(String input) {
// String[] config = StringUtils.split(input, ',');
// if (config == null || config.length < 2) {
// throw new ConfigException("Invalid point: " + input);
// }
// int x = Integer.parseInt(config[0].trim());
// int y = Integer.parseInt(config[1].trim());
// return new Point2i(x, y);
// }
//
// @Override
// public String toString() {
// return "(" + x + ", " + y + ")";
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/org/scorpion/jmugen/core/format/PCXSprite.java
import com.google.common.io.LittleEndianDataInputStream;
import org.scorpion.jmugen.core.maths.Point2i;
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*;
package org.scorpion.jmugen.core.format;
public class PCXSprite implements Sprite {
protected byte[] data;
protected PCXPalette palette;
protected PCXHeader pcxHeader; | protected Point2i offset; |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/format/PCXSprite.java | // Path: src/main/java/org/scorpion/jmugen/core/maths/Point2i.java
// public class Point2i {
// public int x, y;
//
// public Point2i(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// public static Point2i fromString(String input) {
// String[] config = StringUtils.split(input, ',');
// if (config == null || config.length < 2) {
// throw new ConfigException("Invalid point: " + input);
// }
// int x = Integer.parseInt(config[0].trim());
// int y = Integer.parseInt(config[1].trim());
// return new Point2i(x, y);
// }
//
// @Override
// public String toString() {
// return "(" + x + ", " + y + ")";
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.common.io.LittleEndianDataInputStream;
import org.scorpion.jmugen.core.maths.Point2i;
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*; | * 68 2 16-color palette interpretation (unreliable)
* 70 2 horizontal screen resolution - 1 (unreliable)
* 72 2 vertical screen resolution - 1 (unreliable)
* 74 54 reserved, must be zero
*/
public static final class PCXHeader {
public static final int HEADER_SIZE = 128;
public final byte bitsPerPixelPerPlane;
public final byte numOfColorPlanes;
public final short width;
public final short height;
public final short bytesPerRow;
public PCXHeader(byte[] pcxData) {
try (LittleEndianDataInputStream input = new LittleEndianDataInputStream(new ByteArrayInputStream(pcxData))) {
input.skipBytes(3);
bitsPerPixelPerPlane = input.readByte();
short xul = input.readShort();
short yul = input.readShort();
short xlr = input.readShort();
short ylr = input.readShort();
width = (short) (xlr - xul + 1);
height = (short) (ylr - yul + 1);
input.skipBytes(53);
numOfColorPlanes = input.readByte();
bytesPerRow = input.readShort();
input.skipBytes(60);
} catch (IOException e) { | // Path: src/main/java/org/scorpion/jmugen/core/maths/Point2i.java
// public class Point2i {
// public int x, y;
//
// public Point2i(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// public static Point2i fromString(String input) {
// String[] config = StringUtils.split(input, ',');
// if (config == null || config.length < 2) {
// throw new ConfigException("Invalid point: " + input);
// }
// int x = Integer.parseInt(config[0].trim());
// int y = Integer.parseInt(config[1].trim());
// return new Point2i(x, y);
// }
//
// @Override
// public String toString() {
// return "(" + x + ", " + y + ")";
// }
//
// }
//
// Path: src/main/java/org/scorpion/jmugen/exception/GenericIOException.java
// public class GenericIOException extends GenericException {
//
// public GenericIOException(String message) {
// super(message);
// }
//
// public GenericIOException(Throwable cause) {
// super(cause);
// }
//
// public GenericIOException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/org/scorpion/jmugen/core/format/PCXSprite.java
import com.google.common.io.LittleEndianDataInputStream;
import org.scorpion.jmugen.core.maths.Point2i;
import org.scorpion.jmugen.exception.GenericIOException;
import java.io.*;
* 68 2 16-color palette interpretation (unreliable)
* 70 2 horizontal screen resolution - 1 (unreliable)
* 72 2 vertical screen resolution - 1 (unreliable)
* 74 54 reserved, must be zero
*/
public static final class PCXHeader {
public static final int HEADER_SIZE = 128;
public final byte bitsPerPixelPerPlane;
public final byte numOfColorPlanes;
public final short width;
public final short height;
public final short bytesPerRow;
public PCXHeader(byte[] pcxData) {
try (LittleEndianDataInputStream input = new LittleEndianDataInputStream(new ByteArrayInputStream(pcxData))) {
input.skipBytes(3);
bitsPerPixelPerPlane = input.readByte();
short xul = input.readShort();
short yul = input.readShort();
short xlr = input.readShort();
short ylr = input.readShort();
width = (short) (xlr - xul + 1);
height = (short) (ylr - yul + 1);
input.skipBytes(53);
numOfColorPlanes = input.readByte();
bytesPerRow = input.readShort();
input.skipBytes(60);
} catch (IOException e) { | throw new GenericIOException(e); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Rectangle4i.java | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
| import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException; | package org.scorpion.jmugen.core.maths;
public class Rectangle4i {
public final Point2i leftBottom, rightTop;
public Rectangle4i(Point2i leftBottom, Point2i rightTop) {
this.leftBottom = leftBottom;
this.rightTop = rightTop;
}
public static Rectangle4i fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 4) { | // Path: src/main/java/org/scorpion/jmugen/exception/ConfigException.java
// public class ConfigException extends GenericException implements NonFatal {
//
// public ConfigException(String message) {
// super(message, null, false, false);
// }
//
// public static ConfigException missing(String title, String group, String key) {
// StringBuilder sb = new StringBuilder(title)
// .append(": Missing ")
// .append(key);
// if (group != null) {
// sb.append(" in ").append(group);
// }
// return new ConfigException(sb.toString());
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Rectangle4i.java
import org.apache.commons.lang3.StringUtils;
import org.scorpion.jmugen.exception.ConfigException;
package org.scorpion.jmugen.core.maths;
public class Rectangle4i {
public final Point2i leftBottom, rightTop;
public Rectangle4i(Point2i leftBottom, Point2i rightTop) {
this.leftBottom = leftBottom;
this.rightTop = rightTop;
}
public static Rectangle4i fromString(String input) {
String[] config = StringUtils.split(input, ',');
if (config == null || config.length < 4) { | throw new ConfigException("Invalid rectangle: " + input); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/render/Mesh.java | // Path: src/main/java/org/scorpion/jmugen/util/BufferUtils.java
// public class BufferUtils {
//
// public static ByteBuffer toByteBuffer(byte[] bytes) {
// ByteBuffer buffer = ByteBuffer
// .allocateDirect(bytes.length)
// .order(ByteOrder.nativeOrder())
// .put(bytes);
// buffer.flip();
// return buffer;
// }
//
// public static IntBuffer toIntBuffer(int[] ints) {
// IntBuffer buffer = ByteBuffer
// .allocateDirect(ints.length * 4)
// .order(ByteOrder.nativeOrder())
// .asIntBuffer()
// .put(ints);
// buffer.flip();
// return buffer;
// }
//
// public static FloatBuffer toFloatBuffer(float[] floats) {
// FloatBuffer buffer = ByteBuffer
// .allocateDirect(floats.length * 4)
// .order(ByteOrder.nativeOrder())
// .asFloatBuffer()
// .put(floats);
// buffer.flip();
// return buffer;
// }
//
// }
| import org.scorpion.jmugen.util.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*; | package org.scorpion.jmugen.render;
public class Mesh {
private int vao,
vbo,
ebo,
tbo,
count;
public Mesh(float[] vertices, byte[] indices, float[] textureCoord) {
count = indices.length;
vao = glGenVertexArrays();
glBindVertexArray(vao);
// vertex buffer object
vbo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo); | // Path: src/main/java/org/scorpion/jmugen/util/BufferUtils.java
// public class BufferUtils {
//
// public static ByteBuffer toByteBuffer(byte[] bytes) {
// ByteBuffer buffer = ByteBuffer
// .allocateDirect(bytes.length)
// .order(ByteOrder.nativeOrder())
// .put(bytes);
// buffer.flip();
// return buffer;
// }
//
// public static IntBuffer toIntBuffer(int[] ints) {
// IntBuffer buffer = ByteBuffer
// .allocateDirect(ints.length * 4)
// .order(ByteOrder.nativeOrder())
// .asIntBuffer()
// .put(ints);
// buffer.flip();
// return buffer;
// }
//
// public static FloatBuffer toFloatBuffer(float[] floats) {
// FloatBuffer buffer = ByteBuffer
// .allocateDirect(floats.length * 4)
// .order(ByteOrder.nativeOrder())
// .asFloatBuffer()
// .put(floats);
// buffer.flip();
// return buffer;
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/render/Mesh.java
import org.scorpion.jmugen.util.BufferUtils;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
package org.scorpion.jmugen.render;
public class Mesh {
private int vao,
vbo,
ebo,
tbo,
count;
public Mesh(float[] vertices, byte[] indices, float[] textureCoord) {
count = indices.length;
vao = glGenVertexArrays();
glBindVertexArray(vao);
// vertex buffer object
vbo = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vbo); | glBufferData(GL_ARRAY_BUFFER, BufferUtils.toFloatBuffer(vertices), GL_STATIC_DRAW); |
xunnanxu/JMugen | src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java | // Path: src/main/java/org/scorpion/jmugen/util/BufferUtils.java
// public class BufferUtils {
//
// public static ByteBuffer toByteBuffer(byte[] bytes) {
// ByteBuffer buffer = ByteBuffer
// .allocateDirect(bytes.length)
// .order(ByteOrder.nativeOrder())
// .put(bytes);
// buffer.flip();
// return buffer;
// }
//
// public static IntBuffer toIntBuffer(int[] ints) {
// IntBuffer buffer = ByteBuffer
// .allocateDirect(ints.length * 4)
// .order(ByteOrder.nativeOrder())
// .asIntBuffer()
// .put(ints);
// buffer.flip();
// return buffer;
// }
//
// public static FloatBuffer toFloatBuffer(float[] floats) {
// FloatBuffer buffer = ByteBuffer
// .allocateDirect(floats.length * 4)
// .order(ByteOrder.nativeOrder())
// .asFloatBuffer()
// .put(floats);
// buffer.flip();
// return buffer;
// }
//
// }
| import org.scorpion.jmugen.util.BufferUtils;
import java.nio.FloatBuffer; | * 0 0 0 1<br>
*/
public static Matrix4f rotate(float angle) {
Matrix4f m = identity();
float a = (float) Math.toRadians(angle);
float cos = (float) Math.cos(a);
float sin = (float) Math.sin(a);
m.elements[0] = cos;
m.elements[1] = sin;
m.elements[4] = -sin;
m.elements[5] = cos;
return m;
}
public Matrix4f multiply(Matrix4f m2) {
Matrix4f m = new Matrix4f();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
float sum = 0;
for (int k = 0; k < 4; k++) {
sum += elements[i + k * 4] * m2.elements[j * 4 + k];
}
m.elements[i + j * 4] = sum;
}
}
return m;
}
public FloatBuffer toFloatBuffer() {
if (buffer == null) { | // Path: src/main/java/org/scorpion/jmugen/util/BufferUtils.java
// public class BufferUtils {
//
// public static ByteBuffer toByteBuffer(byte[] bytes) {
// ByteBuffer buffer = ByteBuffer
// .allocateDirect(bytes.length)
// .order(ByteOrder.nativeOrder())
// .put(bytes);
// buffer.flip();
// return buffer;
// }
//
// public static IntBuffer toIntBuffer(int[] ints) {
// IntBuffer buffer = ByteBuffer
// .allocateDirect(ints.length * 4)
// .order(ByteOrder.nativeOrder())
// .asIntBuffer()
// .put(ints);
// buffer.flip();
// return buffer;
// }
//
// public static FloatBuffer toFloatBuffer(float[] floats) {
// FloatBuffer buffer = ByteBuffer
// .allocateDirect(floats.length * 4)
// .order(ByteOrder.nativeOrder())
// .asFloatBuffer()
// .put(floats);
// buffer.flip();
// return buffer;
// }
//
// }
// Path: src/main/java/org/scorpion/jmugen/core/maths/Matrix4f.java
import org.scorpion.jmugen.util.BufferUtils;
import java.nio.FloatBuffer;
* 0 0 0 1<br>
*/
public static Matrix4f rotate(float angle) {
Matrix4f m = identity();
float a = (float) Math.toRadians(angle);
float cos = (float) Math.cos(a);
float sin = (float) Math.sin(a);
m.elements[0] = cos;
m.elements[1] = sin;
m.elements[4] = -sin;
m.elements[5] = cos;
return m;
}
public Matrix4f multiply(Matrix4f m2) {
Matrix4f m = new Matrix4f();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
float sum = 0;
for (int k = 0; k < 4; k++) {
sum += elements[i + k * 4] * m2.elements[j * 4 + k];
}
m.elements[i + j * 4] = sum;
}
}
return m;
}
public FloatBuffer toFloatBuffer() {
if (buffer == null) { | buffer = BufferUtils.toFloatBuffer(elements); |
Zuehlke/SHMACK | sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java | // Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
| import static org.junit.Assert.assertEquals;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts.Entry; | package com.zuehlke.shmack.sparkjobs.wordcount;
public class SortedCountAsserter {
protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
final int expectedCount, final T expectedValue) { | // Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
import static org.junit.Assert.assertEquals;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts.Entry;
package com.zuehlke.shmack.sparkjobs.wordcount;
public class SortedCountAsserter {
protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
final int expectedCount, final T expectedValue) { | final Entry<T> entry = sortedCounts.getEntry(position); |
Zuehlke/SHMACK | sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
| import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts; | package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile); | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java
import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts;
package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile); | final SortedCounts<String> sortedCounts = LocalSparkTestRunner.execute(wordCount); |
Zuehlke/SHMACK | sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
| import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts; | package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile); | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java
import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts;
package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile); | final SortedCounts<String> sortedCounts = LocalSparkTestRunner.execute(wordCount); |
Zuehlke/SHMACK | sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
| import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts; | package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile);
final SortedCounts<String> sortedCounts = LocalSparkTestRunner.execute(wordCount);
assertEquals(7446, sortedCounts.size()); | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/SortedCountAsserter.java
// protected static <T> void assertPosition(final SortedCounts<T> sortedCounts, final int position,
// final int expectedCount, final T expectedValue) {
// final Entry<T> entry = sortedCounts.getEntry(position);
// assertEquals(expectedCount, entry.getCount());
// assertEquals(expectedValue, entry.getValue());
// }
//
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestRunner.java
// public class LocalSparkTestRunner {
// public static <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// LocalSparkTestExecutionContext execution = new LocalSparkTestExecutionContext();
// return execution.execute(job);
// }
// }
//
// Path: sparkjobs/src/main/java/com/zuehlke/shmack/sparkjobs/base/SortedCounts.java
// public class SortedCounts<T> implements Iterable<SortedCounts.Entry<T>> , Serializable {
//
// private static final long serialVersionUID = 1;
//
// public static class Entry<T> implements Comparable<Entry<T>>, Serializable {
//
// private static final long serialVersionUID = 1;
//
// private final long count;
// private final T value;
//
// private Entry(final long count, final T value) {
// this.count = count;
// this.value = value;
// }
//
// public long getCount() {
// return count;
// }
//
// public T getValue() {
// return value;
// }
//
// @Override
// public int compareTo(final Entry<T> o) {
// final CompareToBuilder b = new CompareToBuilder();
// b.append(-this.count, -o.count);
// b.append(this.value, o.value);
// return b.toComparison();
// }
// }
//
// private final List<Entry<T>> sortedEntries;
//
// private SortedCounts(final SortedSet<Entry<T>> sortedEntries) {
// this.sortedEntries = new ArrayList<>(sortedEntries);
// }
//
// public static <T, N extends Number> SortedCounts<T> create(final JavaPairRDD<T, N> rdd) {
//
// final SortedSet<Entry<T>> sortedEntries = new TreeSet<>();
// for (final Tuple2<T, N> tuple : rdd.collect()) {
// sortedEntries.add(new Entry<T>(tuple._2.longValue(), tuple._1));
// }
// final SortedCounts<T> result = new SortedCounts<T>(sortedEntries);
//
// return result;
// }
//
// @Override
// public Iterator<Entry<T>> iterator() {
// return sortedEntries.iterator();
// }
//
// public Entry<T> getEntry(int position) {
// return sortedEntries.get(position);
// }
//
// public int size() {
// return sortedEntries.size();
// }
//
// public void print(PrintStream out) {
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// out.println(entryToString(i, entry));
// }
// }
//
// private String entryToString(int i, Entry<T> entry) {
// return i + ".: " + entry.getCount() + ": " + entry.getValue();
// }
//
// @Override
// public String toString() {
// StringBuilder s = new StringBuilder();
// for (int i = 0; i < sortedEntries.size(); i++) {
// Entry<T> entry = sortedEntries.get(i);
// s.append(entryToString(i, entry)).append("\n");
// }
// return s.toString();
// }
//
// }
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/wordcount/WordCountLocalTest.java
import static com.zuehlke.shmack.sparkjobs.wordcount.SortedCountAsserter.assertPosition;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestRunner;
import com.zuehlke.shmack.sparkjobs.base.SortedCounts;
package com.zuehlke.shmack.sparkjobs.wordcount;
public class WordCountLocalTest {
@Test
public void testWordCount() throws Exception {
final String inputFile = "src/test/resources/tweets/tweets_big_data_2000.json";
final WordCount wordCount = new WordCount(inputFile);
final SortedCounts<String> sortedCounts = LocalSparkTestRunner.execute(wordCount);
assertEquals(7446, sortedCounts.size()); | assertPosition(sortedCounts, 19, 126, "analytics"); |
Zuehlke/SHMACK | sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/tutorials/JavaSparkPiLocalTest.java | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestExecutionContext.java
// public class LocalSparkTestExecutionContext {
// private SparkConf conf = new SparkConf()
// .setAppName("LocalSparkTest_NoJobYet")
// .setMaster("local[*]")
// .set("spark.driver.allowMultipleContexts", "true")
// // Not running the Spark UI can speed up testing ... but make debugging harder.
// // So enable depending whether running in debug mode using
// // http://stackoverflow.com/questions/3776204/how-to-find-out-if-debug-mode-is-enabled
// .set("spark.ui.enabled", Boolean.toString(java.lang.management.ManagementFactory.getRuntimeMXBean().
// getInputArguments().toString().indexOf("jdwp") >= 0));
// private JavaSparkContext ctx = new JavaSparkContext(conf);
//
// public JavaSparkContext getSparkContext() {
// return ctx;
// }
//
// public <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// conf.setAppName(job.getApplicationName());
// conf.setIfMissing("spark.master", "local[*]");
// conf.setIfMissing("spark.testing", "true");
//
// return job.execute(ctx);
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestExecutionContext; | package com.zuehlke.shmack.sparkjobs.tutorials;
public class JavaSparkPiLocalTest {
private final static Logger LOGGER = LoggerFactory.getLogger(JavaSparkPiLocalTest.class); | // Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/base/LocalSparkTestExecutionContext.java
// public class LocalSparkTestExecutionContext {
// private SparkConf conf = new SparkConf()
// .setAppName("LocalSparkTest_NoJobYet")
// .setMaster("local[*]")
// .set("spark.driver.allowMultipleContexts", "true")
// // Not running the Spark UI can speed up testing ... but make debugging harder.
// // So enable depending whether running in debug mode using
// // http://stackoverflow.com/questions/3776204/how-to-find-out-if-debug-mode-is-enabled
// .set("spark.ui.enabled", Boolean.toString(java.lang.management.ManagementFactory.getRuntimeMXBean().
// getInputArguments().toString().indexOf("jdwp") >= 0));
// private JavaSparkContext ctx = new JavaSparkContext(conf);
//
// public JavaSparkContext getSparkContext() {
// return ctx;
// }
//
// public <ResultType> ResultType execute(TestableSparkJob<ResultType> job) {
// conf.setAppName(job.getApplicationName());
// conf.setIfMissing("spark.master", "local[*]");
// conf.setIfMissing("spark.testing", "true");
//
// return job.execute(ctx);
// }
// }
// Path: sparkjobs/src/test/java/com/zuehlke/shmack/sparkjobs/tutorials/JavaSparkPiLocalTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zuehlke.shmack.sparkjobs.base.LocalSparkTestExecutionContext;
package com.zuehlke.shmack.sparkjobs.tutorials;
public class JavaSparkPiLocalTest {
private final static Logger LOGGER = LoggerFactory.getLogger(JavaSparkPiLocalTest.class); | private static LocalSparkTestExecutionContext sparkTestExecution = new LocalSparkTestExecutionContext(); |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/BasePen.java | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
| import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo; | */
public void setFillColor(int color) {
if (mFillPaint != null) {
mFillPaint.setColor(color);
}
}
public void setStrokeThickness(int thickness){
if(mStrokePaint != null){
mStrokeThickness = thickness;
mStrokePaint.setStrokeWidth(thickness);
}
}
public void setCapType(Paint.Cap cap){
mStrokePaint.setStrokeCap(cap);
}
public void setJoinType(Paint.Join join){
mStrokePaint.setStrokeJoin(join);
}
/**
* Handles the event action down.
*
* @param x x coordinate of event
* @param y y coordinate of event
* @return <code>IUndo</code> implementation, to make the effect of the
* action undoable.
*/ | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/BasePen.java
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
*/
public void setFillColor(int color) {
if (mFillPaint != null) {
mFillPaint.setColor(color);
}
}
public void setStrokeThickness(int thickness){
if(mStrokePaint != null){
mStrokeThickness = thickness;
mStrokePaint.setStrokeWidth(thickness);
}
}
public void setCapType(Paint.Cap cap){
mStrokePaint.setStrokeCap(cap);
}
public void setJoinType(Paint.Join join){
mStrokePaint.setStrokeJoin(join);
}
/**
* Handles the event action down.
*
* @param x x coordinate of event
* @param y y coordinate of event
* @return <code>IUndo</code> implementation, to make the effect of the
* action undoable.
*/ | protected abstract IUndo handleDownAction(float x, float y); |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/dialogs/ColorPickerDialog.java | // Path: app/src/main/java/jgh/artistex/views/PaletteView.java
// public class PaletteView extends View {
//
// private int mColor;
//
// public PaletteView(Context context) {
// super(context);
// init();
// }
//
// public PaletteView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public PaletteView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init();
// }
//
// private void init() {
// this.setBackgroundColor(mColor);
// }
//
// public void setColor(int color) {
// mColor = color;
// }
//
// protected void onDraw(Canvas canvas) {
// this.setBackgroundColor(mColor);
// }
//
// }
| import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import jgh.artistex.R;
import jgh.artistex.views.PaletteView; | package jgh.artistex.dialogs;
/**
* Dialog class for choosing color. Dialog contains sliders for ARGB selection,
* and a <code>View</code> to see the current color.
* The <code>ColorSetCallbackHandler</code> object handles what to do
* when the color is chosen.
*/
public final class ColorPickerDialog extends BasicDialog implements View.OnClickListener {
/*
* Seekbars for the ARGB channels.
*/
private SeekBar mAlphaSeek, mRedSeek, mGreenSeek, mBlueSeek;
/**
* Select button for finalizing the current selection.
*/
private Button mSelectButton;
/**
* The given color. i.e. the default color
*/
private int mColor;
/**
* Currently selected ARGB values.
*/
private int mAlpha, mRed, mGreen, mBlue;
private ColorSetCallbackHandler mCallbackHandler;
| // Path: app/src/main/java/jgh/artistex/views/PaletteView.java
// public class PaletteView extends View {
//
// private int mColor;
//
// public PaletteView(Context context) {
// super(context);
// init();
// }
//
// public PaletteView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init();
// }
//
// public PaletteView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init();
// }
//
// private void init() {
// this.setBackgroundColor(mColor);
// }
//
// public void setColor(int color) {
// mColor = color;
// }
//
// protected void onDraw(Canvas canvas) {
// this.setBackgroundColor(mColor);
// }
//
// }
// Path: app/src/main/java/jgh/artistex/dialogs/ColorPickerDialog.java
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import jgh.artistex.R;
import jgh.artistex.views.PaletteView;
package jgh.artistex.dialogs;
/**
* Dialog class for choosing color. Dialog contains sliders for ARGB selection,
* and a <code>View</code> to see the current color.
* The <code>ColorSetCallbackHandler</code> object handles what to do
* when the color is chosen.
*/
public final class ColorPickerDialog extends BasicDialog implements View.OnClickListener {
/*
* Seekbars for the ARGB channels.
*/
private SeekBar mAlphaSeek, mRedSeek, mGreenSeek, mBlueSeek;
/**
* Select button for finalizing the current selection.
*/
private Button mSelectButton;
/**
* The given color. i.e. the default color
*/
private int mColor;
/**
* Currently selected ARGB values.
*/
private int mAlpha, mRed, mGreen, mBlue;
private ColorSetCallbackHandler mCallbackHandler;
| private PaletteView mPaletteView; |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/ILayer.java | // Path: app/src/main/java/jgh/artistex/engine/visitors/ILayerVisitor.java
// public interface ILayerVisitor {
//
// void visit(ILayer layer);
//
// /**
// * Visit layers extending the <code>BasePen</code> layer.
// *
// * @param basePen <code>BasePen</code> layer.
// */
// void visitPen(BasePen basePen);
//
//
// /**
// * Visits <code>BitmapLayer</code> layers.
// *
// * @param layer
// */
// void visitBitmap(BaseBitmapLayer layer);
//
//
// /**
// * Visits <code>TextLayer</code> layers.
// *
// * @param layer
// */
// void visitText(TextLayer layer);
// }
| import android.graphics.Canvas;
import android.view.MotionEvent;
import jgh.artistex.engine.visitors.ILayerVisitor; | package jgh.artistex.engine;
/**
* Interface for layers. A layer is an object that
* can be drawn on a canvas, and manipulated by the user and MotionEvents.
*/
public interface ILayer {
/**
* Signals the <code>ILayer</code> implementation to start being manipulated by the user
* This indicates the lyaer has been set as the currently manipulated layer.
*/
void setStart();
/**
* Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
* This indicates that another <code>ILayer</code> implementation is set as the currently
* manipulated layer.
*/
void setStop();
/**
* Draw the Layer on the given canvas.
*
* @param canvas drawing canvas
*/
void draw(Canvas canvas, boolean showTransformBox);
/**
* Applies a motion event to the layer.
* Effect of the motion event is left to
* implementation.
*
* @param event motion event
* @return An <code>IUndo</code> object, making the given effect undoable.
*/
IUndo onEvent(MotionEvent event);
/**
* Returns the <code>LayerType</code> of the Layer.
*
* @return layer type enum
*/
LayerType getLayerType();
/**
* Returns a string tag, to represent this Layer type or uniquely identify this
* Layer.
*
* @return string tag
*/
String getTag();
/**
* Sets the Layer tag to identify this layer or layer type.
*
* @param tag
*/
void setTag(String tag);
/**
* Makes a duplicate copy of this layer.
*
* @return duplicate copy.
*/
ILayer copy();
/**
* Serializes the layer into an SVG (XML) formatted string, for exporting.
*
* @return SVG string represtining this layer.
*/
String getXml();
/**
* Accepts a visit by the <code>ILayerVisitor</code> implementation.
*
* @param visitor Visitor object.
*/ | // Path: app/src/main/java/jgh/artistex/engine/visitors/ILayerVisitor.java
// public interface ILayerVisitor {
//
// void visit(ILayer layer);
//
// /**
// * Visit layers extending the <code>BasePen</code> layer.
// *
// * @param basePen <code>BasePen</code> layer.
// */
// void visitPen(BasePen basePen);
//
//
// /**
// * Visits <code>BitmapLayer</code> layers.
// *
// * @param layer
// */
// void visitBitmap(BaseBitmapLayer layer);
//
//
// /**
// * Visits <code>TextLayer</code> layers.
// *
// * @param layer
// */
// void visitText(TextLayer layer);
// }
// Path: app/src/main/java/jgh/artistex/engine/ILayer.java
import android.graphics.Canvas;
import android.view.MotionEvent;
import jgh.artistex.engine.visitors.ILayerVisitor;
package jgh.artistex.engine;
/**
* Interface for layers. A layer is an object that
* can be drawn on a canvas, and manipulated by the user and MotionEvents.
*/
public interface ILayer {
/**
* Signals the <code>ILayer</code> implementation to start being manipulated by the user
* This indicates the lyaer has been set as the currently manipulated layer.
*/
void setStart();
/**
* Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
* This indicates that another <code>ILayer</code> implementation is set as the currently
* manipulated layer.
*/
void setStop();
/**
* Draw the Layer on the given canvas.
*
* @param canvas drawing canvas
*/
void draw(Canvas canvas, boolean showTransformBox);
/**
* Applies a motion event to the layer.
* Effect of the motion event is left to
* implementation.
*
* @param event motion event
* @return An <code>IUndo</code> object, making the given effect undoable.
*/
IUndo onEvent(MotionEvent event);
/**
* Returns the <code>LayerType</code> of the Layer.
*
* @return layer type enum
*/
LayerType getLayerType();
/**
* Returns a string tag, to represent this Layer type or uniquely identify this
* Layer.
*
* @return string tag
*/
String getTag();
/**
* Sets the Layer tag to identify this layer or layer type.
*
* @param tag
*/
void setTag(String tag);
/**
* Makes a duplicate copy of this layer.
*
* @return duplicate copy.
*/
ILayer copy();
/**
* Serializes the layer into an SVG (XML) formatted string, for exporting.
*
* @return SVG string represtining this layer.
*/
String getXml();
/**
* Accepts a visit by the <code>ILayerVisitor</code> implementation.
*
* @param visitor Visitor object.
*/ | void accept(ILayerVisitor visitor); |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/dialogs/RenameDialog.java | // Path: app/src/main/java/jgh/artistex/engine/utils/Toaster.java
// public class Toaster {
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeShortToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
// }
//
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeShortToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeLongToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeLongToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
//
// }
// }
| import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import jgh.artistex.R;
import jgh.artistex.engine.utils.Toaster; | package jgh.artistex.dialogs;
/**
*
*/
public class RenameDialog extends BasicDialog implements View.OnClickListener {
Button mCompleteButton;
EditText mRenameEditText;
private String mPath;
private String mExt ="";
public RenameDialog(Activity activity, String path, String extension) {
super(activity, R.layout.dialog_rename);
mCompleteButton = (Button) getLayout().findViewById(R.id.completebutton);
mRenameEditText = (EditText) getLayout().findViewById(R.id.rename_edittext);
mCompleteButton.setOnClickListener(this);
mPath = path;
mExt = extension;
getDialog().show();
}
@Override
public void onClick(View v) {
String str = mRenameEditText.getText().toString().trim();
if (str == null || str.isEmpty()) { | // Path: app/src/main/java/jgh/artistex/engine/utils/Toaster.java
// public class Toaster {
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeShortToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
// }
//
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeShortToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeLongToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeLongToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
//
// }
// }
// Path: app/src/main/java/jgh/artistex/dialogs/RenameDialog.java
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import jgh.artistex.R;
import jgh.artistex.engine.utils.Toaster;
package jgh.artistex.dialogs;
/**
*
*/
public class RenameDialog extends BasicDialog implements View.OnClickListener {
Button mCompleteButton;
EditText mRenameEditText;
private String mPath;
private String mExt ="";
public RenameDialog(Activity activity, String path, String extension) {
super(activity, R.layout.dialog_rename);
mCompleteButton = (Button) getLayout().findViewById(R.id.completebutton);
mRenameEditText = (EditText) getLayout().findViewById(R.id.rename_edittext);
mCompleteButton.setOnClickListener(this);
mPath = path;
mExt = extension;
getDialog().show();
}
@Override
public void onClick(View v) {
String str = mRenameEditText.getText().toString().trim();
if (str == null || str.isEmpty()) { | Toaster.makeShortToast(getActivity(), "Unable to rename."); |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/VertexController.java | // Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
| import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler; | package jgh.artistex.engine.Layers.Pens;
/**
* Vertex controller class controls the vertex points, and control points of
* <code>Pen</code> objects. <code>VertexController</code> instances control the manipulation
* of the vertex and control points.
*/
public class VertexController {
/**
* Currently manipulating point.
*/
protected PointF mCurrentPoint = null;
/**
* Paint used for Rects representing vertex coordinates.
*/
protected Paint mPointPaint;
/**
* Padding for drawing rects around vertices.
*/
protected static final int PADDING = 10;
/**
* Default Constructor
*/
public VertexController() {
mPointPaint = new Paint(Color.BLUE);
}
/**
* Checks if the given <i>(x,y)</i> coordinates lie on the given vertex, with a margin of error
* given.
*
* @param x x coordiante to test
* @param y y coordinate to test
* @param vertex PointF vertex
* @param margin margin around PointF point.
* @return True if on vertex, false otherwise.
*/
protected boolean isOnVertex(float x, float y, PointF vertex, float margin) {
if (x > vertex.x - margin && x < vertex.x + margin
&& y > vertex.y - margin && y < vertex.y + margin) {
return true;
}
return false;
}
/**
* Draw the vertex points on the canvas.
* @param vertexPoints
* @param canvas
*/
public void draw(ArrayList<PointF> vertexPoints, Canvas canvas) {
for (int i = 0; i < vertexPoints.size(); i++) {
PointF point = vertexPoints.get(i);
RectF rect = new RectF(point.x - PADDING, point.y - PADDING,
point.x + PADDING, point.y + PADDING);
canvas.drawRect(rect, mPointPaint);
}
}
/**
* Performs onMotionEvent operation. For pointer down, the next selected vertex is
* taken, if one exists, depending on whether the pointer down action hit a vertex position.
* For move events, the vertex is moved to different coordinates, and for up action
* the vertex is released.
*
* @param event Motion event
* @param pointList list of vertex points
*/ | // Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/VertexController.java
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
package jgh.artistex.engine.Layers.Pens;
/**
* Vertex controller class controls the vertex points, and control points of
* <code>Pen</code> objects. <code>VertexController</code> instances control the manipulation
* of the vertex and control points.
*/
public class VertexController {
/**
* Currently manipulating point.
*/
protected PointF mCurrentPoint = null;
/**
* Paint used for Rects representing vertex coordinates.
*/
protected Paint mPointPaint;
/**
* Padding for drawing rects around vertices.
*/
protected static final int PADDING = 10;
/**
* Default Constructor
*/
public VertexController() {
mPointPaint = new Paint(Color.BLUE);
}
/**
* Checks if the given <i>(x,y)</i> coordinates lie on the given vertex, with a margin of error
* given.
*
* @param x x coordiante to test
* @param y y coordinate to test
* @param vertex PointF vertex
* @param margin margin around PointF point.
* @return True if on vertex, false otherwise.
*/
protected boolean isOnVertex(float x, float y, PointF vertex, float margin) {
if (x > vertex.x - margin && x < vertex.x + margin
&& y > vertex.y - margin && y < vertex.y + margin) {
return true;
}
return false;
}
/**
* Draw the vertex points on the canvas.
* @param vertexPoints
* @param canvas
*/
public void draw(ArrayList<PointF> vertexPoints, Canvas canvas) {
for (int i = 0; i < vertexPoints.size(); i++) {
PointF point = vertexPoints.get(i);
RectF rect = new RectF(point.x - PADDING, point.y - PADDING,
point.x + PADDING, point.y + PADDING);
canvas.drawRect(rect, mPointPaint);
}
}
/**
* Performs onMotionEvent operation. For pointer down, the next selected vertex is
* taken, if one exists, depending on whether the pointer down action hit a vertex position.
* For move events, the vertex is moved to different coordinates, and for up action
* the vertex is released.
*
* @param event Motion event
* @param pointList list of vertex points
*/ | /*default*/ IUndo onMotionEvent(MotionEvent event, ArrayList<PointF> pointList) { |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/VertexController.java | // Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
| import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler; | package jgh.artistex.engine.Layers.Pens;
/**
* Vertex controller class controls the vertex points, and control points of
* <code>Pen</code> objects. <code>VertexController</code> instances control the manipulation
* of the vertex and control points.
*/
public class VertexController {
/**
* Currently manipulating point.
*/
protected PointF mCurrentPoint = null;
/**
* Paint used for Rects representing vertex coordinates.
*/
protected Paint mPointPaint;
/**
* Padding for drawing rects around vertices.
*/
protected static final int PADDING = 10;
/**
* Default Constructor
*/
public VertexController() {
mPointPaint = new Paint(Color.BLUE);
}
/**
* Checks if the given <i>(x,y)</i> coordinates lie on the given vertex, with a margin of error
* given.
*
* @param x x coordiante to test
* @param y y coordinate to test
* @param vertex PointF vertex
* @param margin margin around PointF point.
* @return True if on vertex, false otherwise.
*/
protected boolean isOnVertex(float x, float y, PointF vertex, float margin) {
if (x > vertex.x - margin && x < vertex.x + margin
&& y > vertex.y - margin && y < vertex.y + margin) {
return true;
}
return false;
}
/**
* Draw the vertex points on the canvas.
* @param vertexPoints
* @param canvas
*/
public void draw(ArrayList<PointF> vertexPoints, Canvas canvas) {
for (int i = 0; i < vertexPoints.size(); i++) {
PointF point = vertexPoints.get(i);
RectF rect = new RectF(point.x - PADDING, point.y - PADDING,
point.x + PADDING, point.y + PADDING);
canvas.drawRect(rect, mPointPaint);
}
}
/**
* Performs onMotionEvent operation. For pointer down, the next selected vertex is
* taken, if one exists, depending on whether the pointer down action hit a vertex position.
* For move events, the vertex is moved to different coordinates, and for up action
* the vertex is released.
*
* @param event Motion event
* @param pointList list of vertex points
*/
/*default*/ IUndo onMotionEvent(MotionEvent event, ArrayList<PointF> pointList) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
for (PointF point : pointList) {
if (isOnVertex(event.getX(), event.getY(), point, 45)) {
mCurrentPoint = point;
VertexMoveUndoHandler handler = new VertexMoveUndoHandler();
handler.point = point;
handler.xPos = point.x;
handler.yPos = point.y;
return new IUndo(handler);
}
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mCurrentPoint == null) return null;
else {
mCurrentPoint.set(event.getX(), event.getY());
return null;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mCurrentPoint = null;
return null;
}
return null;
}
| // Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/VertexController.java
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
package jgh.artistex.engine.Layers.Pens;
/**
* Vertex controller class controls the vertex points, and control points of
* <code>Pen</code> objects. <code>VertexController</code> instances control the manipulation
* of the vertex and control points.
*/
public class VertexController {
/**
* Currently manipulating point.
*/
protected PointF mCurrentPoint = null;
/**
* Paint used for Rects representing vertex coordinates.
*/
protected Paint mPointPaint;
/**
* Padding for drawing rects around vertices.
*/
protected static final int PADDING = 10;
/**
* Default Constructor
*/
public VertexController() {
mPointPaint = new Paint(Color.BLUE);
}
/**
* Checks if the given <i>(x,y)</i> coordinates lie on the given vertex, with a margin of error
* given.
*
* @param x x coordiante to test
* @param y y coordinate to test
* @param vertex PointF vertex
* @param margin margin around PointF point.
* @return True if on vertex, false otherwise.
*/
protected boolean isOnVertex(float x, float y, PointF vertex, float margin) {
if (x > vertex.x - margin && x < vertex.x + margin
&& y > vertex.y - margin && y < vertex.y + margin) {
return true;
}
return false;
}
/**
* Draw the vertex points on the canvas.
* @param vertexPoints
* @param canvas
*/
public void draw(ArrayList<PointF> vertexPoints, Canvas canvas) {
for (int i = 0; i < vertexPoints.size(); i++) {
PointF point = vertexPoints.get(i);
RectF rect = new RectF(point.x - PADDING, point.y - PADDING,
point.x + PADDING, point.y + PADDING);
canvas.drawRect(rect, mPointPaint);
}
}
/**
* Performs onMotionEvent operation. For pointer down, the next selected vertex is
* taken, if one exists, depending on whether the pointer down action hit a vertex position.
* For move events, the vertex is moved to different coordinates, and for up action
* the vertex is released.
*
* @param event Motion event
* @param pointList list of vertex points
*/
/*default*/ IUndo onMotionEvent(MotionEvent event, ArrayList<PointF> pointList) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
for (PointF point : pointList) {
if (isOnVertex(event.getX(), event.getY(), point, 45)) {
mCurrentPoint = point;
VertexMoveUndoHandler handler = new VertexMoveUndoHandler();
handler.point = point;
handler.xPos = point.x;
handler.yPos = point.y;
return new IUndo(handler);
}
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mCurrentPoint == null) return null;
else {
mCurrentPoint.set(event.getX(), event.getY());
return null;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mCurrentPoint = null;
return null;
}
return null;
}
| /* default */ class VertexMoveUndoHandler implements IUndoHandler{ |
jonghough/ArtisteX | app/src/test/java/jgh/artistex/DataUtilsTest.java | // Path: app/src/main/java/jgh/artistex/engine/utils/DataUtils.java
// public class DataUtils {
//
// /**
// * Base 64 encodes the given bitmap. The compression format is given by
// * <code>format</code>.
// *
// * @param image the bitmap.
// * @param format compression format
// * @return String representation of base64 encoding of bitmap
// */
// public static String encodeTobase64(Bitmap image, Bitmap.CompressFormat format) {
// if (image == null)
// throw new IllegalArgumentException("Cannot pass null bitmap to encoding method.");
// Bitmap immagex = image;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// immagex.compress(format, 100, baos);
// byte[] b = baos.toByteArray();
// String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
//
// return imageEncoded;
// }
//
//
// /**
// * Decodes the string into a bitmap. String should be a base64 encoding of a
// * bitmap.
// *
// * @param input string
// * @return a bitmap
// */
// public static Bitmap decodeBase64(String input) {
// byte[] decodedByte = Base64.decode(input, 0);
// return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
// }
//
//
// /**
// * Gets the RGB values from the color int (e.g. 32-bit integer represenitng ARGB
// * color value.) THe reuslt is returned as a hex string.
// *
// * @param ARGBcolor some color int
// * @return hex string represenitng RGB values. (the last 3 bytes)
// */
// public static String getRGBHex(int ARGBcolor) {
// String s = Integer.toHexString(ARGBcolor);
// char[] c = s.toCharArray();
// // if argb
// if (c.length == 8) {
// String r = s.substring(2);// remove alpha
// return r;
// } else if (c.length == 6) {//only rgb
// return "000000";
// } else
// return "FFFFFF";// default, white
// }
//
//
// /**
// * Gets the alpha value from a color int, i.e. a 32-bit
// * integer representing ARGB colors. So we get the first byte.
// *
// * @param ARGBcolor color represented as int.
// * @return hex string representing the first byte of the int (i.e. the alpha byte).
// */
// public static String getAlpha(int ARGBcolor) {
// if(ARGBcolor == 0)
// return "00";
// String s = Integer.toHexString(ARGBcolor);
// char[] c = s.toCharArray();
// // if argb
// if (c.length == 8) {
// String r = s.substring(0, 2);// remove rgb
// return r;
// } else if (c.length == 6) {//only rgb
// return "00";
// } else
// return "FF";// default, white
// }
//
// /**
// * Gets a decimal representation of the alpha value. i.e. alpha range is [0,256], so
// * this method returns a float in range [0,1] where 1 is equivalent to 256.
// *
// * @param alphaString alpha string representation (hex)
// * @return floating point between 0 and 1.
// */
// public static float getAlphaDecimal(String alphaString) {
// int alpha = 0;
// try {
// alpha = Integer.valueOf(alphaString, 16);
// float alphaFloat = ((float) alpha) / 256;
// } catch (NumberFormatException e) {
// return 0;
// }
// return alpha;
// }
//
// /**
// * Sends a mail with attached image or file.
// * @param activity
// * @param subj
// * @param mesg
// * @param recipient
// * @param uri
// */
// public static void sendMail(Activity activity, String subj, String mesg, String recipient,
// ArrayList<Uri> uri) {
//
// Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
// String[] recipients = new String[] {
// recipient, "",
// };
// emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
// emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subj);
// emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mesg);
//
// emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uri);
//
// emailIntent.setType("image/jpeg");
// activity.startActivity(Intent.createChooser(emailIntent, "Send Email"));
//
// }
// }
| import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import jgh.artistex.BuildConfig;
import jgh.artistex.engine.utils.DataUtils; | package jgh.artistex;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml")
public class DataUtilsTest {
@Test
public void testAlphaString1(){
int color = 0xFF345678; | // Path: app/src/main/java/jgh/artistex/engine/utils/DataUtils.java
// public class DataUtils {
//
// /**
// * Base 64 encodes the given bitmap. The compression format is given by
// * <code>format</code>.
// *
// * @param image the bitmap.
// * @param format compression format
// * @return String representation of base64 encoding of bitmap
// */
// public static String encodeTobase64(Bitmap image, Bitmap.CompressFormat format) {
// if (image == null)
// throw new IllegalArgumentException("Cannot pass null bitmap to encoding method.");
// Bitmap immagex = image;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// immagex.compress(format, 100, baos);
// byte[] b = baos.toByteArray();
// String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
//
// return imageEncoded;
// }
//
//
// /**
// * Decodes the string into a bitmap. String should be a base64 encoding of a
// * bitmap.
// *
// * @param input string
// * @return a bitmap
// */
// public static Bitmap decodeBase64(String input) {
// byte[] decodedByte = Base64.decode(input, 0);
// return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
// }
//
//
// /**
// * Gets the RGB values from the color int (e.g. 32-bit integer represenitng ARGB
// * color value.) THe reuslt is returned as a hex string.
// *
// * @param ARGBcolor some color int
// * @return hex string represenitng RGB values. (the last 3 bytes)
// */
// public static String getRGBHex(int ARGBcolor) {
// String s = Integer.toHexString(ARGBcolor);
// char[] c = s.toCharArray();
// // if argb
// if (c.length == 8) {
// String r = s.substring(2);// remove alpha
// return r;
// } else if (c.length == 6) {//only rgb
// return "000000";
// } else
// return "FFFFFF";// default, white
// }
//
//
// /**
// * Gets the alpha value from a color int, i.e. a 32-bit
// * integer representing ARGB colors. So we get the first byte.
// *
// * @param ARGBcolor color represented as int.
// * @return hex string representing the first byte of the int (i.e. the alpha byte).
// */
// public static String getAlpha(int ARGBcolor) {
// if(ARGBcolor == 0)
// return "00";
// String s = Integer.toHexString(ARGBcolor);
// char[] c = s.toCharArray();
// // if argb
// if (c.length == 8) {
// String r = s.substring(0, 2);// remove rgb
// return r;
// } else if (c.length == 6) {//only rgb
// return "00";
// } else
// return "FF";// default, white
// }
//
// /**
// * Gets a decimal representation of the alpha value. i.e. alpha range is [0,256], so
// * this method returns a float in range [0,1] where 1 is equivalent to 256.
// *
// * @param alphaString alpha string representation (hex)
// * @return floating point between 0 and 1.
// */
// public static float getAlphaDecimal(String alphaString) {
// int alpha = 0;
// try {
// alpha = Integer.valueOf(alphaString, 16);
// float alphaFloat = ((float) alpha) / 256;
// } catch (NumberFormatException e) {
// return 0;
// }
// return alpha;
// }
//
// /**
// * Sends a mail with attached image or file.
// * @param activity
// * @param subj
// * @param mesg
// * @param recipient
// * @param uri
// */
// public static void sendMail(Activity activity, String subj, String mesg, String recipient,
// ArrayList<Uri> uri) {
//
// Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
// String[] recipients = new String[] {
// recipient, "",
// };
// emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
// emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subj);
// emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mesg);
//
// emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uri);
//
// emailIntent.setType("image/jpeg");
// activity.startActivity(Intent.createChooser(emailIntent, "Send Email"));
//
// }
// }
// Path: app/src/test/java/jgh/artistex/DataUtilsTest.java
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import jgh.artistex.BuildConfig;
import jgh.artistex.engine.utils.DataUtils;
package jgh.artistex;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml")
public class DataUtilsTest {
@Test
public void testAlphaString1(){
int color = 0xFF345678; | String alpha = DataUtils.getAlpha(color); |
jonghough/ArtisteX | app/src/test/java/jgh/artistex/UtilTest.java | // Path: app/src/main/java/jgh/artistex/engine/utils/ColorPicker.java
// public class ColorPicker {
//
//
// /**
// * Gets the alpha component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return alpha int
// */
// public static int getAlpha(int color) {
// return (color >> 24) & 0xFF;
// }
//
//
// /**
// * Gets the red component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return red int
// */
// public static int getRed(int color) {
// return (color & 0x00FF0000) >> 16;
// }
//
//
// /**
// * Gets the green component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return green int
// */
// public static int getBlue(int color) {
// return (color & 0x0000FF00) >> 8;
// }
//
//
// /**
// * Gets the blue component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return blue int
// */
// public static int getGreen(int color) {
// return color & 0x000000FF;
// }
//
//
// /**
// * Sets the alpha value fo the given color (ARGB int).
// *
// * @param color
// * @param alpha
// * @return
// */
// public static int setAlpha(int color, int alpha) {
// return (color & 0x00FFFFFF) | (alpha << 24);
// }
//
//
// /**
// * Sets the red value fo the given color (ARGB int).
// *
// * @param color
// * @param red
// * @return
// */
// public static int setRed(int color, int red) {
// return (color & 0xFF00FFFF) | (red << 16);
// }
//
//
// /**
// * Sets the green value fo the given color (ARGB int).
// *
// * @param color
// * @param green
// * @return
// */
// public static int setGreen(int color, int green) {
// return (color & 0xFFFF00FF) | (green << 8);
// }
//
//
// /**
// * Sets the blue value fo the given color (ARGB int).
// *
// * @param color
// * @param blue
// * @return
// */
// public static int setBlue(int color, int blue) {
// return (color & 0xFFFFFF00) | blue;
// }
// }
| import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import jgh.artistex.BuildConfig;
import jgh.artistex.engine.utils.ColorPicker; | package jgh.artistex;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml")
public class UtilTest{
@Test
public void testARGB1(){
int color = 0xABCDEF01; | // Path: app/src/main/java/jgh/artistex/engine/utils/ColorPicker.java
// public class ColorPicker {
//
//
// /**
// * Gets the alpha component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return alpha int
// */
// public static int getAlpha(int color) {
// return (color >> 24) & 0xFF;
// }
//
//
// /**
// * Gets the red component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return red int
// */
// public static int getRed(int color) {
// return (color & 0x00FF0000) >> 16;
// }
//
//
// /**
// * Gets the green component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return green int
// */
// public static int getBlue(int color) {
// return (color & 0x0000FF00) >> 8;
// }
//
//
// /**
// * Gets the blue component of the ARGB int.
// * Returned value will be in range [0,255]
// *
// * @param color ARGB int
// * @return blue int
// */
// public static int getGreen(int color) {
// return color & 0x000000FF;
// }
//
//
// /**
// * Sets the alpha value fo the given color (ARGB int).
// *
// * @param color
// * @param alpha
// * @return
// */
// public static int setAlpha(int color, int alpha) {
// return (color & 0x00FFFFFF) | (alpha << 24);
// }
//
//
// /**
// * Sets the red value fo the given color (ARGB int).
// *
// * @param color
// * @param red
// * @return
// */
// public static int setRed(int color, int red) {
// return (color & 0xFF00FFFF) | (red << 16);
// }
//
//
// /**
// * Sets the green value fo the given color (ARGB int).
// *
// * @param color
// * @param green
// * @return
// */
// public static int setGreen(int color, int green) {
// return (color & 0xFFFF00FF) | (green << 8);
// }
//
//
// /**
// * Sets the blue value fo the given color (ARGB int).
// *
// * @param color
// * @param blue
// * @return
// */
// public static int setBlue(int color, int blue) {
// return (color & 0xFFFFFF00) | blue;
// }
// }
// Path: app/src/test/java/jgh/artistex/UtilTest.java
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import jgh.artistex.BuildConfig;
import jgh.artistex.engine.utils.ColorPicker;
package jgh.artistex;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml")
public class UtilTest{
@Test
public void testARGB1(){
int color = 0xABCDEF01; | int alpha = ColorPicker.getAlpha(color); |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
| import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType; | mFillPaint.setColor(0x00FFFFFF);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
mVertexController = new VertexController();
}
private Pencil(Paint strokePaint, Paint fillPaint, ArrayList<PointF> bezierPoints,
ArrayList<PointF> vertexPoints) {
mVertexList = new ArrayList<>();
mBezierVertexList = new ArrayList<>();
mPath = new Path();
mStrokePaint = new Paint(strokePaint);
mFillPaint = new Paint(fillPaint);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
for(PointF p : bezierPoints){
mBezierVertexList.add(new PointF(p.x, p.y));
}
for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType;
mFillPaint.setColor(0x00FFFFFF);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
mVertexController = new VertexController();
}
private Pencil(Paint strokePaint, Paint fillPaint, ArrayList<PointF> bezierPoints,
ArrayList<PointF> vertexPoints) {
mVertexList = new ArrayList<>();
mBezierVertexList = new ArrayList<>();
mPath = new Path();
mStrokePaint = new Paint(strokePaint);
mFillPaint = new Paint(fillPaint);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
for(PointF p : bezierPoints){
mBezierVertexList.add(new PointF(p.x, p.y));
}
for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override | public ILayer copy(){ |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
| import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType; | }
private Pencil(Paint strokePaint, Paint fillPaint, ArrayList<PointF> bezierPoints,
ArrayList<PointF> vertexPoints) {
mVertexList = new ArrayList<>();
mBezierVertexList = new ArrayList<>();
mPath = new Path();
mStrokePaint = new Paint(strokePaint);
mFillPaint = new Paint(fillPaint);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
for(PointF p : bezierPoints){
mBezierVertexList.add(new PointF(p.x, p.y));
}
for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override
public ILayer copy(){
Pencil pencil = new Pencil(mStrokePaint, mFillPaint, mBezierVertexList, mVertexList);
return pencil;
}
@Override | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType;
}
private Pencil(Paint strokePaint, Paint fillPaint, ArrayList<PointF> bezierPoints,
ArrayList<PointF> vertexPoints) {
mVertexList = new ArrayList<>();
mBezierVertexList = new ArrayList<>();
mPath = new Path();
mStrokePaint = new Paint(strokePaint);
mFillPaint = new Paint(fillPaint);
mTransformer = new PenTransformer(this);
mRotMatrix = new Matrix();
mLastPosition = new PointF();
mBezierController = new BezierController();
for(PointF p : bezierPoints){
mBezierVertexList.add(new PointF(p.x, p.y));
}
for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override
public ILayer copy(){
Pencil pencil = new Pencil(mStrokePaint, mFillPaint, mBezierVertexList, mVertexList);
return pencil;
}
@Override | protected IUndo handleMoveAction(float x, float y) { |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
| import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType; | for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override
public ILayer copy(){
Pencil pencil = new Pencil(mStrokePaint, mFillPaint, mBezierVertexList, mVertexList);
return pencil;
}
@Override
protected IUndo handleMoveAction(float x, float y) {
PointF lastPoint = null;
if (mVertexList.isEmpty() == false) {
lastPoint = mVertexList.get(mVertexList.size() - 1);
}
final PointF newPoint = new PointF(x, y);
mVertexList.add(newPoint);
//bezier
if (lastPoint != null) {
final PointF b1 = new PointF(0.6667f * x + 0.3333f * lastPoint.x, 0.6667f * y + 0.3333f * lastPoint.y);
final PointF b2 = new PointF(0.6667f * lastPoint.x + 0.3333f * x, 0.6667f * lastPoint.y + 0.3333f * y);
mBezierVertexList.add(b1);
mBezierVertexList.add(b2);
| // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType;
for(PointF p : vertexPoints){
mVertexList.add(new PointF(p.x, p.y));
}
mVertexController = new VertexController();
mSet = true;
}
@Override
public ILayer copy(){
Pencil pencil = new Pencil(mStrokePaint, mFillPaint, mBezierVertexList, mVertexList);
return pencil;
}
@Override
protected IUndo handleMoveAction(float x, float y) {
PointF lastPoint = null;
if (mVertexList.isEmpty() == false) {
lastPoint = mVertexList.get(mVertexList.size() - 1);
}
final PointF newPoint = new PointF(x, y);
mVertexList.add(newPoint);
//bezier
if (lastPoint != null) {
final PointF b1 = new PointF(0.6667f * x + 0.3333f * lastPoint.x, 0.6667f * y + 0.3333f * lastPoint.y);
final PointF b2 = new PointF(0.6667f * lastPoint.x + 0.3333f * x, 0.6667f * lastPoint.y + 0.3333f * y);
mBezierVertexList.add(b1);
mBezierVertexList.add(b2);
| return new IUndo(new IUndoHandler() { |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
| import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType; | case SCALING:
if (event.getAction() == MotionEvent.ACTION_UP) {
mState = State.IDLE;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTransformer.scale(x, y);
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
}
break;
case MOVING:
if (event.getAction() == MotionEvent.ACTION_UP) {
mState = State.IDLE;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTransformer.translate(x, y);
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
}
break;
case BEZIER:
return mBezierController.onMotionEvent(event, mBezierVertexList);
case VERTEX:
return mVertexController.onMotionEvent(event, mVertexList);
default:
break;
}
return null;
}
@Override | // Path: app/src/main/java/jgh/artistex/engine/ILayer.java
// public interface ILayer {
//
//
//
//
// /**
// * Signals the <code>ILayer</code> implementation to start being manipulated by the user
// * This indicates the lyaer has been set as the currently manipulated layer.
// */
// void setStart();
//
//
// /**
// * Signals the <code>ILayer</code> implementation to stop being manipulated by the user.
// * This indicates that another <code>ILayer</code> implementation is set as the currently
// * manipulated layer.
// */
// void setStop();
//
//
// /**
// * Draw the Layer on the given canvas.
// *
// * @param canvas drawing canvas
// */
// void draw(Canvas canvas, boolean showTransformBox);
//
//
// /**
// * Applies a motion event to the layer.
// * Effect of the motion event is left to
// * implementation.
// *
// * @param event motion event
// * @return An <code>IUndo</code> object, making the given effect undoable.
// */
// IUndo onEvent(MotionEvent event);
//
//
// /**
// * Returns the <code>LayerType</code> of the Layer.
// *
// * @return layer type enum
// */
// LayerType getLayerType();
//
//
// /**
// * Returns a string tag, to represent this Layer type or uniquely identify this
// * Layer.
// *
// * @return string tag
// */
// String getTag();
//
//
// /**
// * Sets the Layer tag to identify this layer or layer type.
// *
// * @param tag
// */
// void setTag(String tag);
//
//
// /**
// * Makes a duplicate copy of this layer.
// *
// * @return duplicate copy.
// */
// ILayer copy();
//
//
// /**
// * Serializes the layer into an SVG (XML) formatted string, for exporting.
// *
// * @return SVG string represtining this layer.
// */
// String getXml();
//
//
// /**
// * Accepts a visit by the <code>ILayerVisitor</code> implementation.
// *
// * @param visitor Visitor object.
// */
// void accept(ILayerVisitor visitor);
//
//
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndo.java
// public final class IUndo {
//
// /**
// * The <code>UndoHandler</code> performs the
// * actual undo and redo operations, defined per implementation.
// */
// private IUndoHandler mUndoHandler;
//
//
// /**
// * Creates an instance of IUndo. A non-null argument must be passed, or an
// * <code>IllegalArgumentException</code> will be thrown.
// *
// * @param undoHandler the undo handler, hadnles the specifics of the undo and redo actions.
// */
// public IUndo(IUndoHandler undoHandler) {
// if (undoHandler == null) throw new IllegalArgumentException("Cannot pass null argument.");
// mUndoHandler = undoHandler;
// }
//
//
// /**
// * Undo action -- should only be called in <code>DrawingEngine</code> because
// * it should be applied after this <code>IUndo</code> instance is popped
// * off the undo stack <b>only</b>.
// */
// /* default */ void undo() {
// mUndoHandler.handleUndo();
// }
//
//
// /**
// * Redo action -- should only be called in <code>DrawingEngine</code>
// */
// /* default */ void redo() {
// mUndoHandler.handleRedo();
// }
// }
//
// Path: app/src/main/java/jgh/artistex/engine/IUndoHandler.java
// public interface IUndoHandler {
//
// /**
// * Handles the undo action.
// */
// void handleUndo();
//
// /**
// * Handles the redo action
// */
// void handleRedo();
// }
//
// Path: app/src/main/java/jgh/artistex/engine/LayerType.java
// public enum LayerType {
//
// PENCIL,
// PEN,
// SHAPE,
// TEXT,
// IMAGE
// }
// Path: app/src/main/java/jgh/artistex/engine/Layers/Pens/Pencil.java
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import java.util.ArrayList;
import jgh.artistex.engine.ILayer;
import jgh.artistex.engine.IUndo;
import jgh.artistex.engine.IUndoHandler;
import jgh.artistex.engine.LayerType;
case SCALING:
if (event.getAction() == MotionEvent.ACTION_UP) {
mState = State.IDLE;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTransformer.scale(x, y);
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
}
break;
case MOVING:
if (event.getAction() == MotionEvent.ACTION_UP) {
mState = State.IDLE;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTransformer.translate(x, y);
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
}
break;
case BEZIER:
return mBezierController.onMotionEvent(event, mBezierVertexList);
case VERTEX:
return mVertexController.onMotionEvent(event, mVertexList);
default:
break;
}
return null;
}
@Override | public LayerType getLayerType() { |
jonghough/ArtisteX | app/src/main/java/jgh/artistex/dialogs/ShapeDialog.java | // Path: app/src/main/java/jgh/artistex/engine/utils/Toaster.java
// public class Toaster {
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeShortToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
// }
//
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeShortToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeLongToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeLongToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
//
// }
// }
| import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import jgh.artistex.R;
import jgh.artistex.engine.utils.Toaster; | package jgh.artistex.dialogs;
public class ShapeDialog extends BasicDialog implements View.OnClickListener{
private Button mButton;
private RadioGroup mRadioGroup;
private EditText mEditText;
private ShapeSetCallbackHandler mOnClickHandler;
/**
* Instantiates a dialog instance.
*
* @param activity caller activity
*/
public ShapeDialog(Activity activity, ShapeSetCallbackHandler onClickHandler) {
super(activity, R.layout.dialog_shape);
mRadioGroup = (RadioGroup)getLayout().findViewById(R.id.shape_group);
mButton = (Button)getLayout().findViewById(R.id.selectbutton);
mEditText = (EditText) getLayout().findViewById(R.id.numberpicker);
mButton.setOnClickListener(this);
mOnClickHandler = onClickHandler;
getDialog().show();
}
@Override
public void onClick(View v) {
int id = mRadioGroup.getCheckedRadioButtonId();
if(mEditText.getText().toString() == null || mEditText.getText().toString().isEmpty()){ | // Path: app/src/main/java/jgh/artistex/engine/utils/Toaster.java
// public class Toaster {
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeShortToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
// }
//
//
// /**
// * Makes a short duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeShortToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
//
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message id.
// */
// public static void makeLongToast(Activity activity, int message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
// }
//
//
// /**
// * Makes a long duration toast message
// *
// * @param activity Activity
// * @param message message string.
// */
// public static void makeLongToast(Activity activity, String message) {
// Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
//
// }
// }
// Path: app/src/main/java/jgh/artistex/dialogs/ShapeDialog.java
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import jgh.artistex.R;
import jgh.artistex.engine.utils.Toaster;
package jgh.artistex.dialogs;
public class ShapeDialog extends BasicDialog implements View.OnClickListener{
private Button mButton;
private RadioGroup mRadioGroup;
private EditText mEditText;
private ShapeSetCallbackHandler mOnClickHandler;
/**
* Instantiates a dialog instance.
*
* @param activity caller activity
*/
public ShapeDialog(Activity activity, ShapeSetCallbackHandler onClickHandler) {
super(activity, R.layout.dialog_shape);
mRadioGroup = (RadioGroup)getLayout().findViewById(R.id.shape_group);
mButton = (Button)getLayout().findViewById(R.id.selectbutton);
mEditText = (EditText) getLayout().findViewById(R.id.numberpicker);
mButton.setOnClickListener(this);
mOnClickHandler = onClickHandler;
getDialog().show();
}
@Override
public void onClick(View v) {
int id = mRadioGroup.getCheckedRadioButtonId();
if(mEditText.getText().toString() == null || mEditText.getText().toString().isEmpty()){ | Toaster.makeShortToast(getActivity(), "Please input number of points."); |
melrief/HFSP | src/test/java/org/apache/hadoop/mapred/TestHFSP.java | // Path: src/main/java/org/apache/hadoop/mapred/HFSPScheduler.java
// enum QueueType {
// TRAIN, SIZE_BASED
// };
| import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.apache.hadoop.mapred.HFSPScheduler.QueueType;
import org.apache.hadoop.mapred.UtilsForTests.FakeClock;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test; | }
/**
* Check state after job submission and correct assignment of tasks on empty
* slots
*/
@Test
public void testSubmitJobAndAssignTask() throws IOException {
this.advanceTime(1000);
JobInProgress submittedJIP = this.submitJob(JobStatus.RUNNING, 1, 1);
assertTrue(this.scheduler.getJobs(null).iterator().next()
.equals(submittedJIP));
List<Task> tasks = this.scheduler.assignTasks(tracker("tt1"));
assertTrue(tasks.size() == 2);
}
/**
* Complete 1 task of 2 and check that the job is marked as ready and removed
* from training
*/
@Test
public void testTrainToSizeBased() throws IOException {
this.advanceTime(1000);
JobInProgress jip = this.submitJob(JobStatus.RUNNING, 2, 2);
assertTrue(!this.scheduler.isJobReadyForSizeBased(jip, TaskType.MAP)); | // Path: src/main/java/org/apache/hadoop/mapred/HFSPScheduler.java
// enum QueueType {
// TRAIN, SIZE_BASED
// };
// Path: src/test/java/org/apache/hadoop/mapred/TestHFSP.java
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.apache.hadoop.mapred.HFSPScheduler.QueueType;
import org.apache.hadoop.mapred.UtilsForTests.FakeClock;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
}
/**
* Check state after job submission and correct assignment of tasks on empty
* slots
*/
@Test
public void testSubmitJobAndAssignTask() throws IOException {
this.advanceTime(1000);
JobInProgress submittedJIP = this.submitJob(JobStatus.RUNNING, 1, 1);
assertTrue(this.scheduler.getJobs(null).iterator().next()
.equals(submittedJIP));
List<Task> tasks = this.scheduler.assignTasks(tracker("tt1"));
assertTrue(tasks.size() == 2);
}
/**
* Complete 1 task of 2 and check that the job is marked as ready and removed
* from training
*/
@Test
public void testTrainToSizeBased() throws IOException {
this.advanceTime(1000);
JobInProgress jip = this.submitJob(JobStatus.RUNNING, 2, 2);
assertTrue(!this.scheduler.isJobReadyForSizeBased(jip, TaskType.MAP)); | assertTrue(this.scheduler.getJob(jip.getJobID(), QueueType.TRAIN, |
melrief/HFSP | src/main/java/org/apache/hadoop/mapred/AssignTasksHelper.java | // Path: src/main/java/org/apache/hadoop/mapred/HFSPScheduler.java
// enum QueueType {
// TRAIN, SIZE_BASED
// };
| import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.hadoop.mapred.HFSPScheduler.QueueType;
import org.apache.hadoop.mapreduce.TaskType; | private HFSPScheduler scheduler;
LinkedList<Task> result = new LinkedList<Task>();
TaskTrackerStatus ttStatus = null;
HelperForType mapHelper = new HelperForType(TaskType.MAP);
HelperForType reduceHelper = new HelperForType(TaskType.REDUCE);
public long currentTime;
HelperForType helper(TaskType type) {
return type == TaskType.MAP ? this.mapHelper : this.reduceHelper;
}
public AssignTasksHelper(HFSPScheduler scheduler) {
this.scheduler = scheduler;
}
public void init(TaskTrackerStatus ttStatus) {
this.result.clear();
this.ttStatus = ttStatus;
this.currentTime = scheduler.getClock().getTime();
for (TaskType type : HFSPScheduler.TASK_TYPES)
this.helper(type).clear();
this.initTaskStatuses();
for (TaskType type : HFSPScheduler.TASK_TYPES) {
boolean isMap = type == TaskType.MAP;
HelperForType helper = this.helper(type);
this.setStartAvailableSlots(type, isMap ? ttStatus.getAvailableMapSlots()
: ttStatus.getAvailableReduceSlots());
helper.runningTrainTasks = scheduler.getNumRunningTasksNotSuspended( | // Path: src/main/java/org/apache/hadoop/mapred/HFSPScheduler.java
// enum QueueType {
// TRAIN, SIZE_BASED
// };
// Path: src/main/java/org/apache/hadoop/mapred/AssignTasksHelper.java
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.hadoop.mapred.HFSPScheduler.QueueType;
import org.apache.hadoop.mapreduce.TaskType;
private HFSPScheduler scheduler;
LinkedList<Task> result = new LinkedList<Task>();
TaskTrackerStatus ttStatus = null;
HelperForType mapHelper = new HelperForType(TaskType.MAP);
HelperForType reduceHelper = new HelperForType(TaskType.REDUCE);
public long currentTime;
HelperForType helper(TaskType type) {
return type == TaskType.MAP ? this.mapHelper : this.reduceHelper;
}
public AssignTasksHelper(HFSPScheduler scheduler) {
this.scheduler = scheduler;
}
public void init(TaskTrackerStatus ttStatus) {
this.result.clear();
this.ttStatus = ttStatus;
this.currentTime = scheduler.getClock().getTime();
for (TaskType type : HFSPScheduler.TASK_TYPES)
this.helper(type).clear();
this.initTaskStatuses();
for (TaskType type : HFSPScheduler.TASK_TYPES) {
boolean isMap = type == TaskType.MAP;
HelperForType helper = this.helper(type);
this.setStartAvailableSlots(type, isMap ? ttStatus.getAvailableMapSlots()
: ttStatus.getAvailableReduceSlots());
helper.runningTrainTasks = scheduler.getNumRunningTasksNotSuspended( | QueueType.TRAIN, type); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class), | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class), | ClassConfiguration.class); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class), | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class), | StringCollectionConfiguration.class); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration( | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration( | Boolean.class, BooleanConfiguration.class); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration( | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration( | Integer.class, IntConfiguration.class); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration(
Integer.class, IntConfiguration.class);
public final static FieldType<IntegerRanges> IntegerRanges = registerNewConfiguration( | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration(
Integer.class, IntConfiguration.class);
public final static FieldType<IntegerRanges> IntegerRanges = registerNewConfiguration( | IntegerRanges.class, IntegerRangesConfiguration.class); |
melrief/HFSP | src/main/java/org/apache/hadoop/conf/FieldType.java | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration; | package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration(
Integer.class, IntConfiguration.class);
public final static FieldType<IntegerRanges> IntegerRanges = registerNewConfiguration(
IntegerRanges.class, IntegerRangesConfiguration.class);
public final static FieldType<Long> Long = registerNewConfiguration( | // Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class BooleanConfiguration extends ConfigurationDescription<Boolean> {
//
// public BooleanConfiguration(String key, String description,
// Boolean defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Boolean get(Configuration conf) {
// return conf.getBoolean(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class ClassConfiguration extends ConfigurationDescription<Class<?>> {
//
// public ClassConfiguration(String key, String description,
// Class<?> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Class<?> get(Configuration conf) {
// return conf.getClass(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class FloatConfiguration extends ConfigurationDescription<Float> {
//
// public FloatConfiguration(String key, String description, Float defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Float get(Configuration conf) {
// return conf.getFloat(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntConfiguration extends ConfigurationDescription<Integer> {
//
// public IntConfiguration(String key, String description, Integer defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Integer get(Configuration conf) {
// return conf.getInt(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class IntegerRangesConfiguration extends
// ConfigurationDescription<IntegerRanges> {
//
// public IntegerRangesConfiguration(String key, String description,
// IntegerRanges defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected IntegerRanges get(Configuration conf) {
// return conf.getRange(this.getKey(), this.getDefaultValue().toString());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class LongConfiguration extends ConfigurationDescription<Long> {
//
// public LongConfiguration(String key, String description, Long defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Long get(Configuration conf) {
// return conf.getLong(this.getKey(), this.getDefaultValue());
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringCollectionConfiguration extends
// ConfigurationDescription<Collection<String>> {
//
// public StringCollectionConfiguration(String key, String description,
// Collection<String> defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected Collection<String> get(Configuration conf) {
// Collection<String> value = conf.getStringCollection(this.getKey());
// return value.isEmpty() ? this.getDefaultValue() : value;
// }
//
// }
//
// Path: src/main/java/org/apache/hadoop/conf/ConfigurationDescription.java
// static class StringConfiguration extends ConfigurationDescription<String> {
//
// public StringConfiguration(String key, String description,
// String defaultValue) {
// super(key, description, defaultValue);
// }
//
// @Override
// protected String get(Configuration conf) {
// return conf.get(this.getKey(), this.getDefaultValue());
// }
//
// }
// Path: src/main/java/org/apache/hadoop/conf/FieldType.java
import java.util.Collection;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration.IntegerRanges;
import org.apache.hadoop.conf.ConfigurationDescription.BooleanConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.ClassConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.FloatConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.IntegerRangesConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.LongConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringCollectionConfiguration;
import org.apache.hadoop.conf.ConfigurationDescription.StringConfiguration;
package org.apache.hadoop.conf;
public class FieldType<T> {
static HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>> saferRegisteredClasses = new HashMap<FieldType<?>, Class<? extends ConfigurationDescription<?>>>();
static {
saferRegisteredClasses.put(new FieldType<Class>(Class.class),
ClassConfiguration.class);
// saferRegisteredClasses.put(new FieldType<Enum>(Enum.class), (Class<?
// extends ConfigurationDescription<?>>) EnumConfiguration.class);
saferRegisteredClasses.put(new FieldType<Collection>(Collection.class),
StringCollectionConfiguration.class);
}
public final static FieldType<Boolean> Boolean = registerNewConfiguration(
Boolean.class, BooleanConfiguration.class);
// public final static FieldType<Class> Class =
// registerNewConfiguration(Class.class, ClassConfiguration.class);
// public final static FieldType<Enum> Enum =
// registerNewConfiguration(Enum.class, EnumConfiguration.class);
public final static FieldType<Integer> Integer = registerNewConfiguration(
Integer.class, IntConfiguration.class);
public final static FieldType<IntegerRanges> IntegerRanges = registerNewConfiguration(
IntegerRanges.class, IntegerRangesConfiguration.class);
public final static FieldType<Long> Long = registerNewConfiguration( | Long.class, LongConfiguration.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.